繁体   English   中英

如何在 Java 中对来自扫描仪的用户输入进行计时,并根据特定时间间隔将该输入放入一个类别中?

[英]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
  1. 在询问之前,使用Instant.now()捕获当前时间;

  2. 在他们按下enter后,立即使用Instant.now()捕获当时的当前时间;

  3. 使用Duration::between获取这两个时刻之间的持续时间。

  4. Duration格式化为所需的格式,例如

    String.format("%ss and %sms", d.getSeconds(), d.toMillisPart())

暂无
暂无

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

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