首页 > 解决方案 > 如何使反应时间在我的 while 循环中工作

问题描述

我正在编写一个项目来计算用户写答案所需的时间。所以我会显示一个问题,你会回答它。之后,我将显示您解决它所需的时间。

但是当我将变量放在我的 while 循环中时,反应时间不起作用。

这是代码:

long startTime = System.currentTimeMillis();
long endTime = System.currentTimeMillis();
long reactionTime = endTime - startTime;
//Q1
System.out.println("Q1");
while (true) {
    System.out.println("What is 1+1: ");
    int ans = scanner.nextInt();
    if (ans == 2) {
        System.out.println("Correct");
        System.out.println(reactionTime + "ms");
        break;
    } else {
        System.out.println("incorrect please try again");

    }
}

标签: java

解决方案


问题是你的结束时间和开始时间基本上是相等的,因为你甚至在问题被问到之前就把它们都拿走了。

要解决它,只需在用户的答案正确时计算所花费的时间。

// take the start time once before the user gets to answer your question
long startTime = System.currentTimeMillis();

//Q1
System.out.println("Q1");
while (true) {
    System.out.println("What is 1+1: ");
    int ans = scanner.nextInt();
    if (ans == 2) {
        System.out.println("Correct");

        // take the end time here, only if the answer of the user is correct
        long endTime = System.currentTimeMillis();
        long reactionTime = endTime - startTime;

        System.out.println(reactionTime + "ms");
    } else {
        System.out.println("incorrect please try again");
    }
}

推荐阅读