1
import java.io.*;
import java.util.Scanner;

public class Solve {
    public static void main(String[] args) {
        int max = 10;
        int i = 0;
        long record = 100000;
        while (i != 100) {
            int x = (int) (Math.random() * max) + 1;
            int y = (int) (Math.random() * max) + 1;
            int solution = x + y;
            long startTime = System.currentTimeMillis();

            while (i != solution) {
                System.out.println("Enter the solution to " + x + "+" + y);
                Scanner sc = new Scanner(System.in);
                i = sc.nextInt();
                if (i != solution) {
                    System.out.println("Incorrect");

                } else {
                    System.out.println("Correct!");
                }
                long endTime = System.currentTimeMillis();
                System.out.println("You took: " + (endTime - startTime) + "ms");

                if (endTime - startTime < record) {
                    record = endTime - startTime;
                    System.out.println("New record time: " + record + "ms");
                }
            }
        }
    }
}

该程序创建一个简单的加法问题并要求用户输入答案。它还跟踪正确回答问题所需的时间。我试图让用户通过输入 100 for i 来结束第一个 while 循环,但是有没有更好的方法来结束这个循环?

4

2 回答 2

2

永远不会跳出内while循环。您的执行路径将卡在那里。一个快速的解决方法是调整内部循环的循环约束:

while (i != solution && i != 100)
于 2013-06-26T01:01:49.937 回答
1

除非 100 也是解决方案,否则它永远不会退出内部循环。最简单的解决方法是在用户输入 100 时跳出该循环,例如:

i = sc.nextInt();
if (i == 100) break; // add this line
if (i!=solution) ...

这样,您将退出不断检查正确答案的内部循环,然后外部循环也将退出。

可能有更好的方法来表明用户已经完成,但这对于这种情况就足够了,因为数字永远不会总和为 100。如果您打算使用可能总和为 100 的更高数字,您可能需要考虑使用作为-1哨兵(如果你到达结果可能是负面的地步,你也必须对此进行调整)。

您可能还想向用户说明 100 是标记值,这样他们就不会猜测如何退出程序:

System.out.println ("Enter the solution to " + x + "+" + y + " or 100 to exit");
于 2013-06-26T00:54:51.000 回答