java - 如何使反应时间在我的 while 循环中工作
问题描述
我正在编写一个项目来计算用户写答案所需的时间。所以我会显示一个问题,你会回答它。之后,我将显示您解决它所需的时间。
但是当我将变量放在我的 while 循环中时,反应时间不起作用。
这是代码:
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");
}
}
解决方案
问题是你的结束时间和开始时间基本上是相等的,因为你甚至在问题被问到之前就把它们都拿走了。
要解决它,只需在用户的答案正确时计算所花费的时间。
// 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");
}
}
推荐阅读
- replace - Python:替换文本文件中的不寻常字符
- ffmpeg - ffmpeg:HLS 到 mp4
- python - Python动态导入问题__import__,importlib导入成功后,使用hasattr()判断对象有时不存在
- python - 如何在 Python 中删除附加到变量的文件
- python - 用beautifulsoup提取html内容,同时保留一些标签
- json - 创建虚拟列和索引以优化 JSON 列中数组的过滤器
- c++11 - Can map::find and iterator::second be used in one condition
- r - semPlot 不会安装在 MacOS 11.4 上的 R/Rstudio 中,因为 OpenMx 不会安装并且它是一个依赖项
- python - 127.0.0.1 - - [30/Jun/2021 03:42:07]“←[33mOPTIONS /projects/addproject HTTP/1.1←[0m”404
- api - 如何使用 ASP.NetCore WebAPI 登录 Blazor WebAssembly?