Java Reference
In-Depth Information
Statement(s)
(loop body)
loop-
continuation-
condition?
true
false
F
IGURE
4.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.
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
do
{
13
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
21
22 System.out.println(
"The sum is "
+ sum);
23 }
24 }
loop
}
while
(data !=
0
);
end loop
Enter an integer (the input ends if it is 0):
Enter an integer (the input ends if it is 0):
Enter an integer (the input ends if it is 0):
Enter an integer (the input ends if it is 0):
The sum is 14
3
5
6
0
Tip
Use the
do-while
loop if you have statements inside the loop that must be executed
at least once,
as in the case of the
do-while
loop in the preceding
TestDoWhile
program. These statements must appear before the loop as well as inside it if you use a
while
loop.