'How do I time the user input from a Scanner in Java, and place that input into a category based on certain time intervals?
I want the user to answer a question, but their input is timed from the prompt to when they press enter. Then based on how long they took, I want that question and answer pair to be stored somewhere.
Question1: What is the powerhouse of the cell? Answer: Mitochondria The answer is correct, and user took 6 seconds to press enter
Store Question1 into deck A (because all t<10 seconds should be in deck A)
Question2:What is inflammation in the cardiac muscle called? Answer: Myocarditis The answer is correct, and user took 15 seconds to press enter
Store Question2 into deck C. (because all t >=15 seconds but less than 20 should be in deck C)
I can program everything around this problem, I just can't seem to be able to time and store the user input based on that time. Any assistance would be great, thanks!
Solution 1:[1]
I think you simply can save the time before and after you read the user input. I created a small example for one of your questions:
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create a Scanner object
System.out.println("What is the powerhouse of the cell?"); // First question
long startTime = System.currentTimeMillis(); // Save start time
String answer = scanner.nextLine(); // Read user input
long endTime = System.currentTimeMillis(); // Save time after enter
long questionTime = (endTime - startTime) / 1000; // Calculate difference and convert to seconds
if (answer.equals("Mitochondria")) { // Check if answer is correct and print output
System.out.println("The answer is correct, and user took " + questionTime + " seconds to press enter");
} else {
System.out.println("The answer is wrong, and user took " + questionTime + " seconds to press enter");
}
}
}
Console log:
What is the powerhouse of the cell?
Mitochondria
The answer is correct, and user took 3 seconds to press enter
Solution 2:[2]
Right before asking, capture the current time using
Instant.now();Right after they press enter, capture the then current time using
Instant.now();Use
Duration::betweento get the duration between those two instants.Format the
Durationto the desired format, e.g.String.format("%ss and %sms", d.getSeconds(), d.toMillisPart())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JANO |
| Solution 2 | MC Emperor |
