【发布时间】:2016-05-20 01:28:59
【问题描述】:
有谁知道为什么控制台输出在打印exception 之前再显示一次菜单?
我除了输出应该是:
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:
但是,我得到的是:
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?
代码如下:
// 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);
【问题讨论】:
-
可以添加
scanner的初始化吗? -
scanner的初始化在do-while循环之上。但仍然得到这个不正确的流程 -
@TDG 是的,我从 Eclipse 运行它。我附上了上面的输出屏幕。
-
我不知道为什么 Eclipse 会这样。从命令行运行它,一切都会好起来的。