you have the following errors which in turn cause this exception, let me explain this
this is your existing code:
if(!scan.hasNextInt()) { System.out.println("Invalid input!"); System.out.print("Enter an integer: "); usrInput= sc.nextInt(); }
in the above code, if(!scan.hasNextInt()) will only become true when user input contains both characters and integers, such as your adfd 123 input.
but you are trying to read only integers inside the if condition using usrInput= sc.nextInt(); . Which is wrong, that throws an Exception in thread "main" java.util.InputMismatchException .
therefore the correct code should be
if(!scan.hasNextInt()) { System.out.println("Invalid input!"); System.out.print("Enter an integer: "); sc.next(); continue; }
in the above code, sc.next() will help to read the new input from the user, and continue will help to fulfill the if ( ie if(!scan.hasNextInt()) ) condition again.
Please use the code in your first answer to build your complete logic. If I need any explanation, I know.
Rajendra_Prasad
source share