Java Reference
In-Depth Information
int roll2 = r.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
}
We had to prime the loop by setting sum to 0 so that the computer would enter the
loop. With a do/while loop, we can eliminate the priming:
Random r = new Random();
int sum;
do {
// roll the dice once
int roll1 = r.nextInt(6) + 1;
int roll2 = r.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
} while (sum != 7);
In this version, we always execute the body of the loop at least once, which ends
up giving a value to the variable sum before it reaches the loop test that now appears
at the bottom of the loop.
There are many programming problems in which using do/while loops is appropri-
ate. These loops are often useful in interactive programs where you know you want to
do something at least once. For example, you might have a loop that allows a user to
play a game multiple times; you can be fairly sure that the user will want to play at least
once. Likewise, if you are playing a guessing game with the user, you will always have
to obtain at least one guess.
5.2 Fencepost Algorithms
A common programming problem involves a particular kind of loop known as a
fencepost loop. Consider the following problem: You want to put up a fence that is 100
yards long, and you want to install a post every 10 yards. How many posts do you
need? If you do a quick division in your head, you might think that you need 10 posts,
but actually you need 11 posts. That's because fences begin and end with posts. In other
words, a fence looks like Figure 5.3.
Figure 5.3
A typical fence
 
 
Search WWH ::




Custom Search