Java Reference
In-Depth Information
Random r = new Random();
while (sum != 7) {
// roll the dice once
int roll1 = r.nextInt(6) + 1;
int roll2 = r.nextInt(6) + 1;
int sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
}
The preceding code produces the following compiler error:
Dice.java:7: cannot find symbol
symbol : variable sum
location: class Dice
while (sum != 7) {
^
1 error
The problem is that the while loop test refers to the variable sum , but the variable
is declared inside the body of the loop. We can't declare the variable in the inner
scope because we need to refer to it in the loop test. So we have to move the variable
declaration before the loop. We also have to give the variable an initial value to guar-
antee that it enters the loop. This code is another example of a time when we need to
prime the loop:
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;
int roll2 = r.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
}
This version of the code compiles and works properly. A sample execution follows:
1 + 4 = 5
5 + 6 = 11
1 + 3 = 4
4 + 3 = 7
do/while Loop
The while loop is the standard indefinite loop, but Java provides several alternatives.
This section presents the do/while loop. Other variations are included in Appendix D.
 
Search WWH ::




Custom Search