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?