Java Reference
In-Depth Information
L ISTING 5.5
SentinelValue.java
1 import java.util.Scanner;
2
3 public class SentinelValue {
4 /** Main method */
5 public static void main(String[] args) {
6 // Create a Scanner
7 Scanner input = new Scanner(System.in);
8
9 // Read an initial data
10 System.out.print(
11
"Enter an integer (the input ends if it is 0): " );
12
int data = input.nextInt();
input
13
14 // Keep reading data until the input is 0
15 int sum = 0 ;
16 while (data != 0 ) {
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
loop
end of loop
}
24
25 System.out.println( "The sum is " + sum);
26 }
27 }
display result
Enter an integer (the input ends if it is 0): 2
Enter an integer (the input ends if it is 0): 3
Enter an integer (the input ends if it is 0): 4
Enter an integer (the input ends if it is 0): 0
The sum is 9
line#
output
Data
sum
12
2
15
0
17
2
iteration 1
22
3
17
5
iteration 2
22
4
17
9
iteration 3
22
0
25
The sum is 9
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 .
 
Search WWH ::




Custom Search