I'm making a scenario where I only want to accept 1 or 2 as input and also handling errors if another number is entered or if the input is not valid. For this I'm doing:
do {
try {
System.out.println("Enter 1 or 2");
option = input.nextInt();
} catch (InputMismatchException ex) {
System.out.println("Invalid menu number entered. A valid menu option is required. Enter you choice again: ");
//option = input.nextInt(); //The error occurs here
}
} while(!(option == 2 || option == 1));
If I add option = input.nextInt();
in catch
it gives an error as the scope of option is within try. I want it to keep on asking user to input a valid number i.e. 1 or 2, but if I enter any character e
it goes into InputMismatchException
and exit.