Sentinel Values and Input Validation Loops
You'll learn how to use special values to control loops and repeatedly prompt users until they provide valid input.
What Are Sentinel Values?
A sentinel value is a special input that signals "stop processing." Think of it like a "STOP" sign at the end of a street—it tells the loop when to quit. Common examples include -1 to end a list of positive numbers, or "quit" to exit a menu.
int number = 0;
int sum = 0;
while (number != -1) { // -1 is the sentinel
System.out.println("Enter a number (-1 to stop):");
// (imagine reading from user)
number = /* user input */;
if (number != -1) {
sum += number;
}
}
System.out.println("Sum: " + sum);
Input Validation Loops
Input validation ensures users provide acceptable data before your program continues. A while loop keeps asking until the input is valid:
int age = -1; // Start with invalid value
while (age < 0 || age > 120) {
System.out.println("Enter your age (0-120):");
// (imagine reading from user)
age = /* user input */;
if (age < 0 || age > 120) {
System.out.println("Invalid! Try again.");
}
}
System.out.println("Age accepted: " + age);
The loop condition checks for invalid input. As long as the input fails validation, the loop continues asking.
Common Pattern: Combining Both
You can validate each input and use a sentinel to stop:
int grade = 0;
while (grade != -1) {
System.out.println("Enter grade (0-100, -1 to finish):");
// (imagine reading)
grade = /* user input */;
while (grade < -1 || grade > 100) { // Validation loop
System.out.println("Invalid grade! Enter 0-100 or -1:");
grade = /* user input */;
}
if (grade != -1) {
// Process valid grade
}
}
Key Takeaway: Use sentinel values as loop-ending signals and while loops to repeatedly validate input until users provide acceptable data—the loop condition defines what's unacceptable, keeping the program safe from bad input.