Reputation: 1
normally when I get a user interaction from a keyboard I use class scanner to do so but the problem I noticed when using its methods is that it's not handling exception! For example
Scanner input = new scanner();
Int number = input.nextInt();
The above works good for all integer numbers but if the user mistakly entered a character or a string, it will throw an exception and stops executing the rest of the program.
My question is there any way to avoid this?
Thank you in advance.
Upvotes: 0
Views: 88
Reputation: 44808
Try to catch the exception. Or use the hasNextInt
method to prevent the exception from being thrown in the first place.
try {
int number = input.nextInt();
} catch (InputMismatchException e) {
System.out.println("That wasn't a number!");
}
Upvotes: 1
Reputation: 8028
Perhaps you should catch the exception and ask the user again?
See http://www.functionx.com/java/Lesson14.htm for exactly your problem.
Upvotes: 0