简体   繁体   中英

How can I make the reactionTime work in my while loop

I'm programming a project which calculates the time that it takes the user to write the answer. So I will display a question and you'll answer it. After that, I will display the time it takes for you to solve it.

But the reaction time is not working when I put the variables inside my while loop.

Here is the code:

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

    }
}

The problem is that your end time and your start time are basically equal because you take both of them before the question is even asked.

To solve it, only calculate the time it took, once the answer of the user is correct.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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