Does anyone have idea why the console output show the menu one more time before printing the exception
out?
I except the output should be:
1. item 1
2. item 2
3. Quit
Please choose a item:
WRONGINPUT <---- user input
Invalid input <---- where I want the exception shows
1. item 1
2. item 2
3. Quit
Please choose a item:
However, what I get is:
1. item 1
2. item 2
3. Quit
Please choose a item:
WRONGINPUT <---- user input
1. item 1
2. item 2
3. Quit
Please choose a item:
Invalid input <---- why the exception is shown here?
The code is shown below:
// code omitted
Scanner scanner = new Scanner(System.in);
int mainMenu = -1;
do {
try {
System.out.println("1. item 1");
System.out.println("2. item 2");
System.out.println("3. Quit");
System.out.println("Please choose a item:");
mainMenu = scanner.nextInt();
} catch (InputMismatchException e) {
scanner.nextLine();
System.err.println("Invalid input");
}
if (mainMenu == 1)
// do something
else if (mainMenu == 2)
// do something
else if (mainMenu == 3)
System.out.println("Quitting...");
} while (mainMenu != 3);