Java Reference
In-Depth Information
Statement(s)
(loop body)
loop-
continuation-
condition?
true
false
F IGURE 5.2
The do-while loop executes the loop body first, then checks the loop-
continuation-condition to determine whether to continue or terminate the loop.
loop terminates. The difference between a while loop and a do - while loop is the order in
which the loop-continuation-condition is evaluated and the loop body executed. You
can write a loop using either the while loop or the do - while loop. Sometimes one is a more
convenient choice than the other. For example, you can rewrite the while loop in ListingĀ 5.5
using a do - while loop, as shown in ListingĀ 5.6.
L ISTING 5.6
TestDoWhile.java
1 import java.util.Scanner;
2
3 public class TestDoWhile {
4
/** Main method */
5
public static void main(String[] args) {
6
int data;
7
int sum = 0 ;
8
9 // Create a Scanner
10 Scanner input = new Scanner(System.in);
11
12 // Keep reading data until the input is 0
13 do {
14 // Read the next data
15 System.out.print(
16 "Enter an integer (the input ends if it is 0): " );
17 data = input.nextInt();
18
19 sum += data;
20
loop
} while (data != 0 );
end loop
21
22 System.out.println( "The sum is " + sum);
23 }
24 }
Enter an integer (the input ends if it is 0): 3
Enter an integer (the input ends if it is 0): 5
Enter an integer (the input ends if it is 0): 6
Enter an integer (the input ends if it is 0): 0
The sum is 14
 
 
Search WWH ::




Custom Search