Reputation: 95
This is my loop. It repeats endlessly if a non-int is entered. From what I can see, it seems like the exception isn't cleared on the next run of the loop. Or because it takes the previous input and assigns it to menuChoice. How can I fix this?
while(!console.hasNextInt())
{
try {
menuChoice = console.nextInt();
} catch(InputMismatchException e) {
System.out.println("The selection you made is invalid.");
}
}
Upvotes: 0
Views: 188
Reputation: 1105
this might be faster because hasNextInt()
and nextInt()
both try to parse the next token to an int. In this solution the parse is only done once:
while(console.hasNext()){
try {
menuChoice = console.nextInt();
} catch(InputMismatchException e) {
System.out.println("The selection you made is invalid.");
} finally {
//throw away non-ints
console.next();
}
}
Upvotes: 0
Reputation: 23179
don't check for an int in the while loop, check for any input token:
while(console.hasNext()){
if(console.hasNextInt()){
try {
menuChoice = console.nextInt();
} catch(InputMismatchException e) {
System.out.println("The selection you made is invalid.");
}
}else{
//throw away non-ints
console.next();
}
}
Upvotes: 3