简体   繁体   English

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

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

New to Java and learning how to use While loops and random generator. Java 新手,正在学习如何使用 While 循环和随机生成器。 This prints a multiplication question.这将打印一个乘法问题。 Every time the user answers a question wrong, it should print the same question.每次用户回答错误时,它应该打印相同的问题。 Instead, it exits the program.相反,它退出程序。 What should I do?我该怎么办?

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

If you want to repeat the same question when the user gets the answer wrong, you should use another while inside your main loop.如果您想在用户回答错误时重复相同的问题,您应该在主循环中使用另一个while

This inner loop continues to ask as long as you give a wrong answer.只要你给出错误的答案,这个内部循环就会继续提问。

I also replaced nextInt with nextLine , which reads in a whole line of text.我还用nextLine替换了nextInt ,它读取了一整行文本。 This consumes the "Enter" key and is a safer approach at reading from the console.这会消耗“Enter”键,并且是从控制台读取的更安全的方法。 Since the result is now a String you need to use Integer.parseInt to convert it to an int .由于结果现在是一个String您需要使用Integer.parseInt将其转换为int This throws an exception if you enter anything but a whole number so I wrapped it into a try-catch block.如果您输入除整数以外的任何内容,则会引发异常,因此我将其包装到try-catch块中。

If you want, you can add an additional check for validating user input.如果需要,您可以添加额外的检查以验证用户输入。 So in case the user wants to stop playing they only need to input "exit" and the whole outer loop will exit.所以如果用户想停止播放,他们只需要输入“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");
        }
    }
}

Avoid while true.避免同时为真。 Declare a variable to true, pass the variable to the condición loop and set it to false when the answer is incorrect.将变量声明为 true,将该变量传递给 condición 循环,并在答案不正确时将其设置为 false。 You can use break too, but is easier to read the code when you use a exit condition in the while.您也可以使用 break,但在 while 中使用退出条件时更容易阅读代码。 Also read more about loops https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html另请阅读有关循环的更多信息https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

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

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