The SENTINEL
is a constant that has the specific purpose of being the value that breaks out of a loop.
You define it at the top of a program next to the other constants in all caps like this:
int SENTINEL = 0;
The value of sentinel will usually be 0
or -1
.
Example of a program that uses a SENTINEL
. This program asks the user for numbers until they enter the SENTINEL
. Then, it prints the sum of all the numbers they entered.
int SENTINEL = 0;
public void run() {
int sum = 0;
while (true)
{
int num = readInt("Add a number (input " + SENTINEL + " to stop): ");
if (num == SENTINEL) {
break;
}
sum += num;
}
System.out.println("Sum: " + sum);
}
Note how it uses an if statement that breaks out of the loop when you enter the SENTINEL
.
You could just use a number instead of the SENTINEL
, but that would be a magic number, which is not as good style.