Input Using a Sentinel
• Example problem: averaging an arbitrary number of grades.
• Instead of having the user tell us the number of grades
in advance, we can let the user indicate that there are no more
grades by entering a special sentinal value.
• When we encounter the sentinel, we break out of the loop
• example interaction:
Enter grade (-1 to end): 10
Enter grade (-1 to end): 8
Enter grade (-1 to end): 9
Enter grade (-1 to end): 5
Enter grade (-1 to end): -1
The average is: 8.0
Input Using a Sentinel (cont.)
• Here's one way to do this:
Scanner console = new Scanner(System.in);
int total = 0;
int numGrades = 0;
System.out.print("Enter grade (or -1 to quit): ");
int grade = console.nextInt();
while (grade != -1) {
total += grade;
numGrades++;
System.out.print("Enter grade (or -1 to quit): ");
grade = console.nextInt();
}
if (numGrades > 0) {
System.out.print("The average is ");
System.out.println((double)total/numGrades);
}