Java Reference
In-Depth Information
13
14
// Keep reading data until the input is 0
15
int
sum =
0
;
loop
while
(data !=
0
) {
16
17 sum += data;
18
19
// Read the next data
20 System.out.print(
21
"Enter an integer (the input ends if it is 0): "
);
22 data = input.nextInt();
23
24
25 System.out.println(
"The sum is "
+ sum);
26 }
27 }
}
end of loop
display result
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 9
2
3
4
0
output
line#
data
sum
12
2
15
0
17
2
iteration 1
22
3
17
5
iteration 2
22
4
17
9
iteration 3
22
0
The sum is 9
25
If
data
is not
0
, it is added to
sum
(line 17) and the next item of input data is read (lines
20-22). If
data
is
0
, the loop body is no longer executed and the
while
loop terminates. The
input value
0
is the sentinel value for this loop. Note that if the first input read is
0
, the loop
body never executes, and the resulting sum is
0
.
Caution
Don't use floating-point values for equality checking in a loop control. Because floating-
point values are approximations for some values, using them could result in imprecise
counter values and inaccurate results.
Consider the following code for computing
1 + 0.9 + 0.8 + ... + 0.1
:
double
item =
1
;
double
sum =
0
;
while
(
item !=
0
) {
// No guarantee item will be 0
sum += item;
item -=
0.1
;
}
System.out.println(sum);