The value "0" in this program is the sentinel value. Could any other value be used?
No. You might decide that a special value like "9999" would be a good sentinel, but then what happens if this number happens to occur in the list to be added up?
With the value "0" as the sentinel, if that value occurs in the list to be added, it can be skipped without any problem (since skipping it affects the sum the same way as adding it in.)
Here is the interesting part of the program again, with some additions to make the user prompt more "user friendly:"
int count = 0; // get the first value System.out.println( "Enter first integer (enter 0 to quit):" ); inputData = userin.readLine(); value = Integer.parseInt( inputData ); while ( value != 0 ) { //add value to sum sum = sum + value; //increment the count __________________ //get the next value from the user System.out.println( "Enter the " + (count+1) + "th integer (enter 0 to quit):" ); inputData = userin.readLine(); value = Integer.parseInt( inputData ); } System.out.println( "Sum of the " + count + " integers: " + sum ); } } |
When this modified program is run, the user dialog should look something like the following:
C:\users\default\JavaLessons/chap18>java addUpNumbers Symantec Java! JustInTime Compiler Version 210.063 for JDK 1.1.3 Copyright (C) 1996-97 Symantec Corporation Enter first integer (enter 0 to quit): 12 Enter the 2th integer (enter 0 to quit): -3 Enter the 3th integer (enter 0 to quit): 4 Enter the 4th integer (enter 0 to quit): -10 Enter the 5th integer (enter 0 to quit): 0 Sum of the 4 integers: 3
Additional statements could correct the dubious grammar for the first few integers, but let's not do that now.