Java Reference
In-Depth Information
As we have seen, the
while
loop tests at the “top” of the loop, before it executes
its controlled statement. Java has an alternative known as the
do/while
loop that
tests at the “bottom” of the loop. The
do/while
loop has the following syntax:
do {
<statement>;
...
<statement>;
} while (<test>);
Here is some sample code using a
do/while
loop:
int number = 1;
do {
number *= 2;
} while (number <= 200);
This loop produces the same result as the corresponding
while
loop, doubling the
variable
number
until its value reaches
256
, which is the first power of
2
greater than
200
. But unlike the
while
loop, the
do/while
loop always executes its controlled
statements at least once. The diagram in Figure 5.2 shows the flow of control in a
do/while
loop.
Execute the
controlled statement(s)
Ye s
Is the test true?
No
Execute the statement
after the
do/while
loop
Figure 5.2
Flow of
do/while
loop
The
do/while
loop is most useful in situations in which you know you have to
execute the loop at least once. For example, in the last section we wrote the following
code that simulates the rolling of two dice until you get a sum of 7:
Random r = new Random();
int sum = 0; // set to 0 to make sure we enter the loop
while (sum != 7) {
// roll the dice once
int roll1 = r.nextInt(6) + 1;
Search WWH ::
Custom Search