Common approaches to taking input of more than 1 value include:
- taking input of the number of values.
- using a sentinel to indicate when there are no more values.
Algorithm with a sentinel
declare variables necessary to process the input
prompt for, accept, and store input
while (the input is not the sentinel)
{
process the input
prompt for, accept, and store input
}
A sentinel is a value (or values, possibly a range) that indicates that there are no more values to be processed. The sentinel is entered as input after the last valid value.
The sentinel can be a single value, a range of values, or anything that is not within the set of valid input. The input is processed at the beginning of the loop body. This ensures that only valid input (input other than the sentinel) is processed.
Example with a sentinel
int sum = 0;
Scanner fromKeyboard = new Scanner(System.in);
System.out.print("Enter positive number (non-positive to quit): ");
int input = fromKeyboard.nextInt();
fromKeyboard.nextLine();
while(input > 0)
{
sum += input;
System.out.print("Enter positive number (non-positive to quit): ");
input = fromKeyboard.nextInt();
fromKeyboard.nextLine();
}
fromKeyboard.close();
System.out.println(sum);
The code segment accepts input of positive numbers and computes the sum. The code segment stops accepting input when a non-positive (zero or negative) number is entered.
Common errors
Mishandling the first input
The first input is accepted before the loop and processed at the beginning of the first loop run. If the first input is not accepted before the loop, it is easy to process a value that is not part of the input.
If there are 0 valid inputs, the sentinel is the first value encountered. Processing the first input inside the loop cleanly handles this case.
Processing the input at the end of the loop
Each input is processed at at the beginning of the loop. If the input is processed at the end of the loop, it is easy to process the sentinel.
Choosing a poor sentinel
The sentinel must be outside the set of valid input. Choosing a value within the set of valid input makes it difficult to handle that value as valid input.
Choosing a value of a completely different type (ex: non-numeric) may require special handling.