2016-09-20 9 views
1

私はちょうどJavaでコードを学ぶために始めているとは今、私はさまざまな方法を試してみたと私は同様の質問を見てみたが、私はできませんが、私はのためにこれを把握しようとしました私の答えを見つける。ユーザーが正解を入力したら、このループが繰り返されないようにするにはどうすればよいですか?

正解が入力されると、ユーザの入力は、1に等しい2、または3が続いて繰り返し停止しませんが、私は繰り返すループを取得しようとしています。

// create a menu and display it to the user 
    // then ask the user to choose an option 
    String menu = "1) See Rules\n" 
       + "2) Play the Game\n" 
       + "3) Exit\n" 
       + "Please enter your choice: (1 or 2 or 3) "; 

    String userChoice = JOptionPane.showInputDialog(menu); 

    JOptionPane.showMessageDialog(null, "You chose option " + userChoice); 

    // display the rules 
    String rules = "Rules:\n" 

      + "The game will display total 3 multiple choice questions," + 
      " with 4 possible answers per question.\n" 
      + "Once you answer the question, the correct answer will be displayed" + 
      " and the game will advance to the next question.\n" 
      + "If you answer the question correctly, you will gain a point.\n" 
      + "Each point is added to a total score that will be displayed at the" + 
      "end of the game.\n"; 

// declare an integer that reads the user input 
int numericChoice = Integer.parseInt(userChoice); 

boolean valid = (numericChoice == 1 || numericChoice == 2 || numericChoice == 3); 

while (true) 
{ 
    if (!valid) { 
     JOptionPane.showMessageDialog(null, "Invalid selection, please try again"); 
     JOptionPane.showInputDialog(menu); 
    } if (valid){ 
     break; 
} 

    if (numericChoice == 1){ 
    // display the rules then start the game 
    JOptionPane.showMessageDialog(null, rules); 
    } 
    else if (numericChoice == 2){ 
    // start the game 
    JOptionPane.showMessageDialog(null, "Let's play the game.\n"); 
    } 
    else if (numericChoice == 3) 
    // exit the game 
    System.exit(0); 

助けてください。

+1

あなたはループが – Li357

答えて

1

あなたの問題は、の外側にあり、ループのが有効であるということです。 つまり、一度計算してください。ループに入る前にあなたのループの中であなたは決してその価値にもう一度触れません。

したがって、あなたのループはありません「だけ」の事は何度も何度もそのダイアログを高めることです。

したがって、移動する必要がありますこれらの計算のすべては、ループ内に!

だから、だけでなく、

boolean valid = (numericChoice == 1 || numericChoice == 2 || numericChoice == 3); 

は、ループに行く必要がなく、ユーザー入力を取り出し、コード、およびnumericChoiceを決定!

private int showMenuAndGetUserChoice() { 
// create a menu and display it to the user 
// then ask the user to choose an option 
String menu = "1) See Rules\n" ... 
String userChoice = JOptionPane.showInputDialog(menu); 
JOptionPane.showMessageDialog(null, "You chose option " + userChoice); ... 

return Integer.parseInt(userChoice); 
} 

そして今、単純にそのメソッドを呼び出して、あなたのループ本体内にその結果をチェックして、あなたはループをはるかに容易にすることができます:あなたは何ができるか

は次のように、ヘルパーメソッドを記述することです!

+0

を終了するために期待するべきではありませんので、あなたは 'valid'を変更することはありませんありがとうございました:) –

+0

あなたは歓迎以上です;-) – GhostCat

関連する問題