java - 用户输入正确答案后,如何停止重复此循环?

标签 java eclipse

我才刚刚开始学习用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);

请帮忙。

最佳答案

您的问题是您正在循环之外计算有效。 换句话说:你计算一次;在进入循环之前;然后,在循环中,您再也不会触及它的值。

因此,循环所做的“唯一”事情就是一遍又一遍地引发该对话框。

因此:您必须在循环内移动所有这些计算!

所以,不仅

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);
} 

现在,您可以更轻松地循环,只需调用该方法并在循环体内检查其结果即可!

关于java - 用户输入正确答案后,如何停止重复此循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584320/

相关文章:

java - 按下按钮后更新屏幕

java - 如何在状态栏中获得永久应用程序通知程序?

eclipse - 如何在 Eclipse 中显示 Project Explorer 窗口?

java - 执行 mapreduce 程序时出现 ClassNotFoundException

java - Eclipse 可以自动生成第三方库类的接口(interface)吗?

java - 如何设置JDK版本来编译JSP页面?

java - 在java中的AWS lambda函数中包含访问控制 header

java - 如何使用分水岭改进图像分割?

java - 新的空白 Activity Android 应用程序不工作

java - 如何使用 maven jvmArg 解决 "GC overhead limit exceeded"?