Algorithm
prompt for, accept, and store input
while (the input is invalid)
{
display an error message
prompt for, accept, and store input
}
When the loop terminates (after 0 or more runs) the stored input is valid.
Simple example
The example below assumes that fromKeyboard has been declared and initialized as a Scanner reading from the keyboard.
System.out.print("Enter an integer from 1 to 10 (inclusive): ");
int number = fromKeyboard.nextInt();
fromKeyboard.nextLine();
while(number < 1 || number > 10)
{
System.out.println("\n" + number + " is not within range.");
System.out.print("Enter an integer from 1 to 10 (inclusive): ");
number = fromKeyboard.nextInt();
fromKeyboard.nextLine();
}
System.out.println(number + " is valid");
The variable number stores both the initial input and any subsequent inputs. number is declared and initialized before the loop. Within the loop, number is set to the new input. number is not declared again inside the loop.
The calls to nextLine are intended to remove the line separator from the input stream. Although this example would work without the calls to nextLine, including them allows other code that uses the same Scanner object to take String input without causing the error discussed at Keyboard input with mixed types.
Execution with invalid input
When the code segment above is run with the inputs -5 (invalid), 15 (invalid), then 5 (valid), the interaction is shown below.
Enter an integer from 1 to 10 (inclusive): -5
-5 is not within range.
Enter an integer from 1 to 10 (inclusive): 15
15 is not within range.
Enter an integer from 1 to 10 (inclusive): 5
5 is valid
Execution with valid input first
If the user enters 5 (valid) at the first prompt, the loop condition evaluates to false the first time it is checked and the loop body does not run. This is the desired behavior.
Enter an integer from 1 to 10 (inclusive): 5
5 is valid
Handling non-numeric input
The example above correctly handles any invalid numeric input (ex: -5, 15). If the user enters a non-numeric input (ex: hamster), nextInt crashes with an InputMismatchException.
Input validation as String explains how to handle (invalid) non-numeric input.
Example with specific valid values
System.out.print("Play or quit? (p/q): ");
String response = fromKeyboard.nextLine();
while( ! response.equals("p") && ! response.equals("q") )
{
System.out.println("\nInvalid input");
System.out.print("Play or quit? (p/q): ");
response = fromKeyboard.nextLine();
}
System.out.println("User chose: " + response);
The loop condition checks that the input is not equal to "p" and (&&) not equal to "q". Using or (||) instead would result in a condition that always evaluates to true.