首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Java中对用户从扫描仪输入的时间进行计时,并根据特定的时间间隔将输入放入一个类别中?

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

Stack Overflow用户
提问于 2022-02-23 10:29:42
回答 2查看 200关注 0票数 0

我希望用户回答一个问题,但是他们的输入是从提示符到按enter键的时间。然后根据他们花了多长时间,我想把这个问题和答案放在某个地方。

Question1:牢房的动力是什么?答:线粒体答案是正确的,用户花了6秒按回车。

将Question1存储到A甲板(因为所有的t<10秒都应该在A甲板上)

问题2:心肌中的炎症叫什么?答:心肌炎答案正确,用户花了15秒按回车。

将Question2储存在C甲板(因为所有t >=15秒都应在C甲板上,但小于20秒)

我可以为这个问题编写所有的程序,只是我似乎无法根据这个时间来存储用户输入。任何帮助都是很好的,谢谢!

EN

回答 2

Stack Overflow用户

发布于 2022-02-23 10:42:28

我认为您只需在读取用户输入之前和之后节省时间。我为你的一个问题创造了一个小例子:

代码语言:javascript
运行
复制
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");
        }
    }
}

控制台日志:

代码语言:javascript
运行
复制
What is the powerhouse of the cell?
Mitochondria
The answer is correct, and user took 3 seconds to press enter
票数 2
EN

Stack Overflow用户

发布于 2022-02-23 10:51:28

使用Instant.now();捕获当前时间(

  1. ),然后再询问

在按enter键后,立即使用Instant.now();捕获当前时间。

  1. 使用Duration::between获取这两个瞬间之间的持续时间.

  1. Duration格式化为所需的格式。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71235250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档