Java Reference
In-Depth Information
amounts (assuming that dollar amounts are displayed with two digits to the right of the
decimal point): Two
double
dollar amounts stored in the machine could be 14.234
(which would normally be rounded to 14.23 for display purposes) and 18.673 (which
would normally be rounded to 18.67 for display purposes). When these amounts are add-
ed, they produce the internal sum 32.907, which would normally be rounded to 32.91 for
display purposes. Thus, your output could appear as
14.23
+ 18.67
-------
32.91
but a person adding the individual numbers as displayed would expect the sum to be
32.90. You've been warned!
Error-Prevention Tip 5.6
Do not use variables of type
double
(or
float
) to perform precise monetary calculations.
The imprecision of floating-point numbers can lead to errors. In the exercises, you'll learn
how to use integers to perform precise monetary calculations—Java also provides class
java.math.BigDecimal
for this purpose, which we demonstrate in Fig. 8.16.
The
do
…
while
repetition statement
is similar to the
while
statement. In the
while
, the
program tests the loop-continuation condition at the
beginning
of the loop,
before
execut-
ing the loop's body; if the condition is
false
, the body
never
executes. The
do
…
while
state-
ment tests the loop-continuation condition
after
executing the loop's body; therefore,
the
body always executes at least once
. When a
do
…
while
statement terminates, execution con-
tinues with the next statement in sequence. Figure 5.7 uses a
do
…
while
to output the
numbers 1-10.
1
// Fig. 5.7: DoWhileTest.java
2
// do...while repetition statement.
3
4
public class
DoWhileTest
5
{
6
public static void
main(String[] args)
7
{
8
int
counter =
1
;
9
10
do
{
System.out.printf(
"%d "
, counter);
++counter;
}
while
(counter <=
10
);
// end do...while
11
12
13
14
15
16
System.out.println();
17
}
18
}
// end class DoWhileTest
Fig. 5.7
|
do
…
while
repetition statement. (Part 1 of 2.)