我正在为我的最终项目尝试这个。由于某种原因,我的程序无法识别我正在提示用户输入,并且程序没有为用户输入信息提供空间,而是退出了。代码如下:
int choice;
Scanner input = new Scanner (System.in);
System.out.println("Enter a number between 1 and 4.");
choice = input.nextInt();
if (choice > 0 && choice < 5) {
System.out.print("To return to the main menu, enter 'main'. To return to the Forces Menu, enter 'forces'. To quit, enter 'quit'.");
choice2 = input.nextLine();
if (choice2.compareToIgnoreCase(MM) == 0) {
mainMenu();
} else if (choice2.compareToIgnoreCase(F) == 0) {
forces();
} else if (choice2.compareToIgnoreCase(X) == 0) {
System.out.println("Thank you! Goodbye!");
}
}
MM、F 和 X 只是用户输入第二个选择时要使用的字符串变量。在显示“要返回主菜单...输入‘退出’。”后,程序停止而不是提示用户输入。如果我用 while(choice...) 替换 if(choice...) ,它只会重复提示是否退出或返回的语句。我读过一篇类似的文章,其中建议替换第一个 input.nextInt();与 input.nextLine(); ,但这对我不起作用。顺便说一句,我正在 Netbeans 7.2 中编程。
最佳答案
这是您需要的行
choice = Integer.parseInt(input.nextLine());
而不是choice = input.nextInt();
或者放置
input.nextLine();
在你之后
choice = input.nextInt();
关于java - 程序未确认输入语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13738138/