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 handling exceptions, this code will enter an infinite loop when non-integer input is given. Instead of Scannerpausing to collect input in the next iteration, it just keeps throwing InputMismatchExceptionuntil the program is killed.
What is the best way to scan to input an integer (or another type, I suppose), discard invalid input and continue the loop in normal mode?
Maxpm source
share