Asking for an integer [closed]

When you’re using Scanner.nextInt() the input is expected to be an integer. Inputting anything else, including a real number, will throw an InputMismatchException. To make sure invalid input doesn’t stop your program, use a try/catch to handle the exception:

int num;
try {
    num = sc.nextInt();
    // Continue doing things with num
} catch (InputMismatchException e) {
    // Tell the user the error occured

Leave a Comment