0

我正在为我的最终项目尝试这个。出于某种原因,我的程序没有识别出我正在提示用户输入,并且程序没有给用户输入信息的空间,而是退出了。这是代码:

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 进行编程。

4

1 回答 1

1

这是您需要的行

choice = Integer.parseInt(input.nextLine()); 

代替choice = input.nextInt();

或者放

input.nextLine(); 

在你之后

choice = input.nextInt();

于 2012-12-06T06:36:42.850 回答