sinan bunni
sinan bunni

Reputation: 1

Get an input from user scanner class

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

Answers (2)

Jeffrey
Jeffrey

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

Mikhail
Mikhail

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

Related Questions