[英]How do I time the user input from a Scanner in Java, and place that input into a category based on certain time intervals?
我希望用戶回答一個問題,但他們的輸入是從提示到他們按下回車鍵的時間。 然后根據他們花了多長時間,我希望將問題和答案對存儲在某個地方。
問題一:細胞的動力源是什么? Answer: Mitochondria The answer is correct , and user take 6 seconds to press enter 答案:線粒體答案正確,用戶用了 6 秒按回車
將 Question1 存儲到 deck A(因為所有 t<10 秒都應該在 deck A 中)
問題2:心肌的炎症叫什么? 答案:心肌炎答案正確,用戶用了15 秒按回車
將 Question2 存儲到 deck C 中。(因為所有 t >=15 秒但小於 20 的時間都應該在 deck C 中)
我可以圍繞這個問題編寫所有程序,但我似乎無法根據那個時間來計時和存儲用戶輸入。 任何幫助都會很棒,謝謝!
我認為您可以簡單地節省閱讀用戶輸入前后的時間。 我為你的一個問題創建了一個小例子:
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");
}
}
}
控制台日志:
What is the powerhouse of the cell?
Mitochondria
The answer is correct, and user took 3 seconds to press enter
在詢問之前,使用Instant.now()
捕獲當前時間;
在他們按下enter后,立即使用Instant.now()
捕獲當時的當前時間;
使用Duration::between
獲取這兩個時刻之間的持續時間。
將Duration
格式化為所需的格式,例如
String.format("%ss and %sms", d.getSeconds(), d.toMillisPart())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.