I have the following part of a program, which emulates a very basic menu.
while (true) {
int selection;
try {
selection = scanner.nextInt();
} catch (Exception e) {
selection = -1;
}
switch (selection) {
case 0:
System.exit(0);
default:
System.out.println("No valid selection!");
}
}
Now, whenever I enter not an integer, the selection is set to -1 and the error message is printed. However, the loop continues endlessly, with the Scanner not waiting for any input.
How do I tell it to wait again? How do I fail more gracefully on malformed user input here?
When a
Scannerfails to read something, the offending data is not removed from the stream, which means any subsequent read will fail again until the data is cleared.To fix this, you could, on failure, just read something and ignore the result: