繁体   English   中英

这个java while 循环有什么问题?

[英]What is wrong with this java while loop?

Java 新手,正在学习如何使用 While 循环和随机生成器。 这将打印一个乘法问题。 每次用户回答错误时,它应该打印相同的问题。 相反,它退出程序。 我该怎么办?

while (true) {
    Random multiply = new Random();
    int num1 = multiply.nextInt(15);
    int num2 = multiply.nextInt(15);
    int output = num1 * num2;

    System.out.println("What is the answer to " + num1 + " * " + num2);

    Scanner input = new Scanner(System.in);
    int answer = input.nextInt();
    if (answer == output) {
        if (answer != -1)
            System.out.println("Very good!");
    } else {
        System.out.println("That is incorrect, please try again.");
    }
}

如果您想在用户回答错误时重复相同的问题,您应该在主循环中使用另一个while

只要你给出错误的答案,这个内部循环就会继续提问。

我还用nextLine替换了nextInt ,它读取了一整行文本。 这会消耗“Enter”键,并且是从控制台读取的更安全的方法。 由于结果现在是一个String您需要使用Integer.parseInt将其转换为int 如果您输入除整数以外的任何内容,则会引发异常,因此我将其包装到try-catch块中。

如果需要,您可以添加额外的检查以验证用户输入。 所以如果用户想停止播放,他们只需要输入“exit”,整个外循环就会退出。

boolean running = true; // This flag tracks if the program should be running.
while (running) {
    Random multiply = new Random();
    int num1 = multiply.nextInt(15);
    int num2 = multiply.nextInt(15);
    int output = num1 * num2;
    boolean isCorrect = false; // This flag tracks, if the answer is correct

    while (!isCorrect) {
        System.out.println("What is the answer to " + num1 + " * " + num2);

        Scanner input = new Scanner(System.in);
        try {
            String userInput = input.nextLine(); // Better use nextLine to consume the "Enter" key.
            // If the user wants to stop
            if (userInput.equals("exit")) {
                 running = false; // Don't run program any more
                 break;
            }
            int answer = Integer.parseInt(userInput); 
            if (answer == output) {
                if (answer != -1) {
                    System.out.println("Very good!");
                    isCorrect = true; // Set the flag to true, to break out of the inner loop
                }
            } else {
                System.out.println("That is incorrect, please try again.");
            }
        }
        catch(NumberFormatException e) {
            System.out.println("Please enter only whole numbers");
        }
    }
}

避免同时为真。 将变量声明为 true,将该变量传递给 condición 循环,并在答案不正确时将其设置为 false。 您也可以使用 break,但在 while 中使用退出条件时更容易阅读代码。 另请阅读有关循环的更多信息https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM