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

huangapple go评论74阅读模式
英文:

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("请回答 " + num1 + " * " + num2 + " 等于多少:");

    Scanner input = new Scanner(System.in);
    int answer = input.nextInt();
    if (answer == output) {
        if (answer != -1)
            System.out.println("非常好!");
    } else {
        System.out.println("回答错误,请重试。");
    }
}
英文:

New to Java and learning how to use While loops and random generator. 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.");
    }
}

答案1

得分: 1

如果您希望在用户答错问题时重复相同的问题,您应该在主循环内部使用另一个 while

这个内部循环会在您给出错误答案时不断询问。

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

如果您愿意,您可以添加额外的检查来验证用户输入。这样,如果用户想要停止玩游戏,他们只需要输入“exit”,整个外部循环将退出。

boolean running = true; // 此标志跟踪程序是否应该运行。
while (running) {
    Random multiply = new Random();
    int num1 = multiply.nextInt(15);
    int num2 = multiply.nextInt(15);
    int output = num1 * num2;
    boolean isCorrect = false; // 此标志跟踪答案是否正确

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

        Scanner input = new Scanner(System.in);
        try {
            String userInput = input.nextLine(); // 最好使用 nextLine 来消耗“Enter”键。
            // 如果用户想要停止
            if (userInput.equals("exit")) {
                running = false; // 不再运行程序
                break;
            }
            int answer = Integer.parseInt(userInput); 
            if (answer == output) {
                if (answer != -1) {
                    System.out.println("Very good!");
                    isCorrect = true; // 将标志设置为 true,以跳出内部循环
                }
            } else {
                System.out.println("That is incorrect, please try again.");
            }
        }
        catch(NumberFormatException e) {
            System.out.println("Please enter only whole numbers");
        }
    }
}
英文:

If you want to repeat the same question when the user gets the answer wrong, you should use another while inside your main loop.

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. This consumes the "Enter" key and is a safer approach at reading from the console. Since the result is now a String you need to use Integer.parseInt to convert it to an int. This throws an exception if you enter anything but a whole number so I wrapped it into a try-catch block.

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.

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

答案2

得分: 0

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

英文:

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. You can use break too, but is easier to read the code when you use a exit condition in the while. Also read more about loops https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

huangapple
  • 本文由 发表于 2020年9月14日 03:30:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63874760.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定