Reputation: 38691
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?
Upvotes: 0
Views: 2971
Reputation: 53829
Not sure throwing and catching an exception is relevant in your case.
Try:
boolean isValid = false;
int selection;
while(!isValid) {
isValid = scanner.hasNextInt();
if(!isValid) {
System.out.println("No valid selection!");
scanner.next();
} else {
selection = scanner.nextInt();
}
}
if(selection == 0) {
System.exit(0);
}
Upvotes: 1
Reputation: 36851
When a Scanner
fails 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:
try {
selection = scanner.nextInt();
} catch (Exception e) {
selection = -1;
scanner.next(); // discard the input
}
Upvotes: 6
Reputation: 4324
Make some user input exit out/break the while loop. Like if a user enters "Exit" while loop stops.
Besides that you can do something like:
catch (Exception e) {
selection = -1;
}
switch (selection) {
case 0:
System.exit(0);
default:
System.out.println("No valid selection!");
System.out.println("Try again!");
selection = scanner.nextInt();
}
Upvotes: -3