Scanner scanner = new Scanner();
int number = 1;
do
{
try
{
option = scanner.nextInt();
}
catch (InputMismatchException exception)
{
System.out.println("Integers only, please.");
}
}
while (number != 0);
Despite the exception handling, this code will enter an infinite loop when non-integer input is given. Instead of Scanner pausing to collect input in the next iteration, it simply continues throwing InputMismatchExceptions until the program is killed.
What’s the best way to scan for integer (or another type, I suppose) input, discarding invalid input and continuing the loop normally?
You should check whether or not the input can be parsed as an int before attempting to assign the input’s value to an int. You should not be using an exception to determine whether or not the input is correct it is bad practice and should be avoided.
This way you can check whether or not the input can be interpreted as an int and if so assign the value and if not display a message. Calling that method does not advance the scanner.