Java Reference
In-Depth Information
The output is
1 2 3 4 5 6 7 8 9 10
You cannot write a do-while loop whose body never executes because the body executes
before the boolean expression is tested. For example, try to determine the output of the
following example:
8. char c = 'a';
9. do {
10. System.out.println(c++);
11. }while(false);
12. System.out.println(c);
An 'a' is printed on line 10, and then the boolean expression on line 11 is tested.
Because it is false , the loop terminates. Line 12 prints out a 'b' , so the output is
a
b
In the section on the while statement, I wrote a program that simulated the rolling of
two dice until an 11 is rolled. That example is actually better suited for a do-while loop
because we have to roll the dice at least once. The same loop rewritten using a do statement
follows:
7. int one = 0, two = 0;
8. System.out.print(“You rolled a “);
9. do {
10. one = rollDice();
11. two = rollDice();
12. System.out.print(one + two + “ “);
13. }while(one + two != 11);
The two dice are rolled fi rst, and then we check to see if an 11 was rolled. If not, the
dice are rolled again and again until they add up to 11 . The output looks something like the
following:
You rolled a 7 2 8 5 8 7 5 9 10 10 9 7 8 8 5 11
The output is different each time you run the program because of the use of random
numbers, but the dice are always rolled at least once.
Search WWH ::




Custom Search