1

I have this problem a few times already on other projects as well. Right now I try to understand exception handling but I still don't know how it exactly works. I tried to program a calculator with a loop and when I try to input a String, there will be InputMismatchException - I tried to catch it, but for some reason after the catch clause, java gives me another InputMismatchException, why?

import java.util.InputMismatchException;
import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int loop = 1;
        while (loop == 1) {

            try {

                System.out.println("First number:");
                int num1 = scanner.nextInt();
                System.out.println("Second number:");
                int num2 = scanner.nextInt();

                System.out.println("Choose operator (1 for +)(2 for -)(3 for *)(4 for /): ");

                int userInput = scanner.nextInt();

                switch (userInput) {
                case 1:
                    System.out.println("Result: " + num1 + " + " + num2 + " = " + (num1 + num2));
                    break;
                case 2:
                    System.out.println("Result: " + num1 + " - " + num2 + " = " + (num1 - num2));
                    break;
                case 3:
                    System.out.println("Result: " + num1 + " * " + num2 + " = " + (num1 * num2));
                    break;
                case 4:
                    System.out.println("Result: " + num1 + " / " + num2 + " = " + (num1 / num2));
                    break;
                default:
                    System.out.println("Invalid Input!");

                }

                System.out.println("Repeat? (1 = yes)(0 = nein)");

                loop = scanner.nextInt();

            } catch (InputMismatchException e) {
                System.out.println("Invalid Input, try again!");
                scanner.nextInt();

            }

        }
        scanner.close();
        System.out.println("Ciao!");

    }

}

At first there was an infinite loop, which I solve by scanner.nextInt(); within the catch block, but still I get this error:

Choose operator (1 for +)(2 for -)(3 for *)(4 for /): 
er
Invalid Input, try again!
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Calculator.main(Calculator.java:47)

Why?

Haidepzai
  • 190
  • 1
  • 7

4 Answers4

1

Probably because you did not fetch the nextInt, since the next value was not an int. thus you try to fetch the same input again in your catch block and thus have a InputMismatchException again.

Your Stacktrace also points to the catch clause where you try to retrieve the next int!

I suggest you just replace nextInt in the catch clause with nextLine:

...
catch (InputMismatchException e) {
    System.out.println("Invalid Input, try again!");
    scanner.nextLine();
}

Then you will start your loop again and try to read anew.

Also checkout this similar thread on stackoverflow or the tutorialspoint examples for using the Scanner class.

SSchneid
  • 92
  • 10
  • You are right of cause, so just read and disregard the non-int input by reading the next line and start the loop again adn ask for a new input. I edited the answer. – SSchneid Nov 12 '19 at 13:42
0

In your first case it enters into the infinite loop as InputMismatchException is thrown by scanner.nextInt(); and you have handled that exception so it will again go for next iteration which eventually invokes scanner.nextInt(); again but in that case, the scanner does not move to the new line, so it will get String instead of int which it was expecting and will throw InputMismatchException. You can solve it by :

        catch (InputMismatchException e) {
            System.out.println("Invalid Input, try again!");
            scanner.nextLine(); // change nextInt to nextLine
        }

In your current code when InputMismatchException throws it goes to catch block and your catch block and again it execute scanner.nextInt(); which throw the exception and your loop thread terminate.

Amit Bera
  • 6,464
  • 1
  • 13
  • 37
0
  1. After you catch the exception you should scan the mismatch input. You can use scanner.nextLine() and the scanner will scan the bad input so your loop starts again.
  2. Your program start over after the exception. If you want to continue the loop after the exception you have to use multiple try catch and use do while till the user enter the correct input.
Integer num1 = null;
do {
   try {
     num1 = scanner.nextInt();
   } catch (InputMismatchException e) {
     System.out.println("Invalid Input, try again!");
     scanner.nextLine();
   }
} while (num1 == null);
-1

if we want to catch the exception rather than throwing it outside the method then line which could potentially throw the exception should be in try block like

try{
//code which can throw exception T
}
catch( exceptions T){
// what if exception handle it
} 

but in your case scanner.nextInt(); is producing the exception in try block and control goes to catch block here again you executing same line scanner.nextLine(); which again throw the exception and this time it is not handled remove scanner.nextInt(); line from catch block

SSchneid
  • 92
  • 10