繁体   English   中英

如何使反应时间在我的 while 循环中工作

[英]How can I make the reactionTime work in my while loop

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

但是当我将变量放在我的 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");

    }
}

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

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

// 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");
    }
}
public class Questionnaire {
    
    public static void main(String... args) {
        int totalQuestions = 10;
        Scanner scan = new Scanner(System.in);
        
        for (int i = 0; i < totalQuestions; i++) {
            String title = "What is 1+1: ";
            String correctAnswer = "2";
            long reactionTime = askQuestionAndGetReactionTimeMs(scan, title, correctAnswer);
            System.out.format("Reaction time: %dms\n\n", reactionTime);
        }
    }
    
    private static long askQuestionAndGetReactionTimeMs(Scanner scan, String title, String correctAnswer) {
        long beginTime = System.currentTimeMillis();
        
        while (true) {
            System.out.print(title);
            String answer = scan.next();
            
            if(correctAnswer.equals(answer))
                return System.currentTimeMillis() - beginTime;
            
            System.out.println("incorrect please try again")
        }
    }
}

暂无
暂无

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

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