The problem is that you are using the nextInt () method, which expects an integer as input. You must either check the user input or give instructions for entering the correct numbers.
Using try catch in java:
An exception is simply executing instructions in an unintended / unexpected way. Java handles exceptions with try, catch. The syntax is as follows.
try{ //suspected code }catch(Exception ex){ //resolution }
Put your suspicious code that might throw an exception in the try block. And inside the catch block, put code that solves the problem if something goes wrong when the suspicious code is executed.
You can find a comprehensive description here and a generalized version here .
source share