1

I am facing java.util.InputMismatchException;

I catch InputMismatchException but I don't understand why it is going into infinite loop after taking first wrong input and the output goes on like this:

enter two integers 
exception caught

this goes on repeating

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int flag = 0;
    while (flag != 1) {
        try {
            System.out.println("enter two integers");
            int a = sc.nextInt();
            int b = sc.nextInt();
            int result = a + b;
            flag = 1;
            System.out.println("ans is" + result);
        } catch (NumberFormatException e) {
            System.out.println("exception caught");
        } catch (InputMismatchException e) {
            System.out.println("exception caught");
        }
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269

3 Answers3

2

You need to clear the buffer so that it is not invalid for nextInt() after the exception is thrown. Add a finally block and call sc.nextLine() within it:

while (flag != 1) {
    try {
        System.out.println("enter two integers");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int result = a + b;
        flag = 1;
        System.out.println("ans is" + result);

    } catch (NumberFormatException e) {
        System.out.println("exception caught");
    } catch (InputMismatchException e) {
        System.out.println("exception caught");
    } finally {  //Add this here
        sc.nextLine();
    }
}

Working example: https://ideone.com/57KtFw

Shadow
  • 3,926
  • 5
  • 20
  • 41
  • While this will work for data like `1 2` it will fail for data like `1 2 3` because `nextLine()` is placed in `finally` which means it will consume entire line *even if exception will not be thrown* so it will also consume `3` which may be valid input for later part of application. It is better to handle each exception in catch block, `finally` section is for mandatory tasks which needs to be executed regardless if exception will be thrown or not. – Pshemo Jan 03 '18 at 18:43
0

If you press the enter key you need to consume this character too

int a = sc.nextInt();
int b = sc.nextInt(); 
sc.nextLine ();

then you can enter

2 3 <CR>
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

In your code you are catching InputMisMatchException and you are just printing a message which will result in again going to your while loop.

        int a = sc.nextInt(); 
        int b = sc.nextInt();

When either of these lines throw the exception your flag=1 will not be set and you will be in an infinite loop. Correct your exception handling and either break out of loop or clear your scanner input by reading it as string.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33