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は、ユーザーが2番目の選択肢を入力するときに使用される単なる文字列変数です。「メインメニューに戻るには...「終了」と入力してください。」と表示された後、プログラムはユーザーに入力を求める代わりに停止します。if(choice ...)をwhile(choice ...)に置き換えると、終了するか戻るかを尋ねるステートメントが繰り返されます。最初のinput.nextInt();を置き換えることを提案した同様の投稿を読みました。input.nextLine();を使用しましたが、それは私にはうまくいきませんでした。ちなみに、私はNetbeans7.2でプログラミングしています。

4

1 に答える 1

1

これはあなたが必要とした行です

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

それ以外のchoice = input.nextInt();

または置く

input.nextLine(); 

あなたの後

choice = input.nextInt();

于 2012-12-06T06:36:42.850 に答える