Java Reference
In-Depth Information
Enter deposit amount for account2:
123.45
adding 123.45 to account2 balance
Jane Green balance: $75.53
John Blue balance: $123.45
Fig. 3.9
|
Inputting and outputting floating-point numbers with
Account
objects. (Part 3 of 3.)
Displaying the
Account
Objects' Initial Balances
When method
getBalance
is called for
account1
from line 14, the value of
account1
's
balance
is returned from line 31 of Fig. 3.8 and displayed by the
System.out.printf
statement (Fig. 3.9, lines 13-14). Similarly, when method
getBalance
is called for
account2
from line 16, the value of the
account2
's
balance
is returned from line 31 of
Fig. 3.8 and displayed by the
System.out.printf
statement (Fig. 3.9, lines 15-16). The
balance
of
account2
is initially
0.00
, because the constructor rejected the attempt to start
account2
with a
negative
balance, so the balance retains its default initial value.
Formatting Floating-Point Numbers for Display
Each of the
balance
s is output by
printf
with the format specifier
%.2f
. The
%f
format
specifier
is used to output values of type
float
or
double
. The
.2
between
%
and
f
repre-
sents the number of
decimal places
(
2
) that should be output to the
right
of the decimal
point in the floating-point number—also known as the number's
precision
. Any floating-
point value output with
%.2f
will be
rounded
to the
hundredths position
—for example,
123.457 would be rounded to 123.46 and 27.33379 would be rounded to 27.33.
Reading a Floating-Point Value from the User and Making a Deposit
Line 21 (Fig. 3.9) prompts the user to enter a deposit amount for
account1
. Line 22 de-
clares
local
variable
depositAmount
to store each deposit amount entered by the user. Un-
like
instance
variables (such as
name
and
balance
in class
Account)
,
local
variables (like
depositAmount
in
main
) are
not
initialized by default, so they normally must be initialized
explicitly. As you'll learn momentarily, variable
depositAmount
's initial value will be de-
termined by the user's input.
Common Programming Error 3.1
The Java compiler will issue a compilation error if you attempt to use the value of an un-
initialized local variable. This helps you avoid dangerous execution-time logic errors. It's
always better to get the errors out of your programs at compilation time rather than exe-
cution time.
Line 22 obtains the input from the user by calling
Scanner
object
input
's
nextDouble
method, which returns a
double
value entered by the user. Lines 23-24 display the
depositAmount
. Line 25 calls object
account1
's
deposit
method with the
depositAmount
as the method's
argument
. When the method is called, the argument's value is assigned to
the parameter
depositAmount
of method
deposit
(line 22 of Fig. 3.8); then method
deposit
adds that value to the
balance
. Lines 28-31 (Fig. 3.9) output the
name
s and
bal-
ance
s of both
Account
s
again
to show that
only
account1
's
balance
has changed.