I was running a simple Calculator app to learn Java\'s exception handling. I\'ve set two exceptions to be handled: InputMismatchException and ArithmeticException for divisio
InputMismatchException
is caused by the call to nextInt()
, because the next token is 4+5
.
The token is not consumed by the failed call.
Which means that OP = input.next().charAt(0)
sets OP = '4'
, something that should be very apparent if you debugged the code. See What is a debugger and how can it help me diagnose problems? and How to debug small programs.
You need to discard the failed token(s), e.g. by calling nextLine()
in the catch
clause:
} catch (InputMismatchException e) {
System.err.println("Please space out the expression");
input.nextLine(); // Discard input(s)
} ...