java中如何记录每道题的时间和时长?

如何解决java中如何记录每道题的时间和时长?

我在用多项选择记录测验代码的时间和持续时间时遇到问题。

这是回答完所有问题后最终输出的样本。

问题 # 您的答案备注了时长

1 B 错误 10:32AM 30 秒

2 A 正确 10:33AM 22 秒 //重复直到问题 #5

这是代码:

package timer;
import java.util.Date;
import java.util.Scanner;
import java.text.*;
import java.util.concurrent.TimeUnit;

public class num4 {
public static void main (String [] args) throws InterruptedException{
    
   Scanner scan=new Scanner(System.in); 
    Date date=new Date();
    SimpleDateFormat ft = 
  new SimpleDateFormat ("MMMM dd,yyyy '@'hh:mm a ");
   String one,two,three,four,five;
   String o,t,th,f,fi;
   int variable=0,wrong=0,seconds,minutes;
   final long startTime = System.nanoTime();
   System.out.println("Welcome to the rawr game!\n");
   Thread.sleep(1000);

   System.out.println("Question #1");
   System.out.println("What can one catch that is not thrown?");
   System.out.println("[A] rain");
   System.out.println("[B] a cold");
   System.out.println("[C] a secret");
   System.out.println("[D] snow");
   
    System.out.print("\nYour answer: ");
    one=scan.next();
    if(one.equals("B")){
        o="Correct";
        variable=variable+1;
    }else{
         o="Wrong";
         wrong=wrong+1;
    }
    
   System.out.println("\nQuestion #2");
   System.out.println("Pambansang Editor: ");
   System.out.println("[A] Netflix");
   System.out.println("[B] Youtube");
   System.out.println("[C] Facebook");
   System.out.println("[D] Instagram");
   
   System.out.print("\nYour answer: ");
   two=scan.next();
   if(two.equals("D")){
        t="Correct";
        variable=variable+1;
    }else{
         t="Wrong";
          wrong=wrong+1;
    }
   
   System.out.println("\nQuestion #3");
   System.out.println("Indian's Population in 2020");
   System.out.println("[A] 1.333 billion");
   System.out.println("[B] 1.300 billion");
   System.out.println("[C] 1.333 million");
   System.out.println("[D] 1.336 billion");
   
   System.out.print("\nYour answer: ");
   three=scan.next();
   
   if(three.equals("D")){
        th="Correct";
        variable=variable+1;
    }else{
         th="Wrong";
          wrong=wrong+1;
    }
   
   System.out.println("\nQuestion #4");
   System.out.println("Man's Bestfriend?");
   System.out.println("[A] dogs");
   System.out.println("[B] cat");
   System.out.println("[C] hamster");
   System.out.println("[D] none");
   
   System.out.print("\nYour answer: ");
   four=scan.next();
   if(four.equals("A")){
        f="Correct";
        variable=variable+1;
    }else{
         f="Wrong";
          wrong=wrong+1;
    }
   
   System.out.println("\nQuestion #5");
   System.out.println("Who steal the pot of soup in Episode 100 of Mark Angel Comedy? ");
   System.out.println("[A] Emmanuella");
   System.out.println("[B] The Iphone Girl");
   System.out.println("[C] Denilson");
   System.out.println("[D] Kbrown");
   
   System.out.print("\nYour answer: ");
   five=scan.next();
   if(five.equals("C")){
        fi="Correct";
        variable=variable+1;
    }else{
         fi="Wrong";
          wrong=wrong+1;
    }
   
   

  System.out.println("=====");
  System.out.println("Rawr quiz on " + ft.format(date));
  System.out.println("=====");
  
  System.out.println("Question #\tYour Answer\tRemarks\tTime\tDuration");
  System.out.println("1\t\t"+one+"\t\t"+o);
  System.out.println("2\t\t"+two+"\t\t"+t);
  System.out.println("3\t\t"+three+"\t\t"+th);  ///as you can see in this part
  System.out.println("4\t\t"+four+"\t\t"+f);    //// it's not complete
  System.out.println("5\t\t"+five+"\t\t"+fi);   ///I'm having trouble on how 
                                                /// to get the time and duration
  
  System.out.println("Number of Correct Answers: "+variable+"\t\tNumber of Wrong Answers: "+wrong);

  final long duration = System.nanoTime()- startTime;
  seconds =(int) (duration/1000000000);
  minutes= (int)  (seconds/60);
  if (minutes<=1){
      System.out.println("Total Duration: "+minutes+" minute");
  }else{
      System.out.println("Total Duration: "+minutes+" minutes");
  }
  

 }
 }

解决方法

切勿使用 DateCalendarSimpleDateFormat 类。仅使用 java.time 类进行日期时间处理。

当您开始提问时,捕捉以 UTC 显示的当前时刻。

Instant start = Instant.now() ;

在用户回答后,记录经过的时间。

Duration d = Duration.between( start,Instant.now() ) ;

以整秒计数的形式获取总经过时间。

long seconds = d.toSeconds() ;

Instant 调整到时区以显示给用户。

ZoneId z = ZoneId.systemDefault() ;
ZonedDateTime zdt = instant.atZone( z ) ;

生成文本。

Locale locale = Locale.getDefault() ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale ) ;
String output = zdt.format( f ) ;

在一对数组中跟踪每个问题的开始和持续时间。或者定义您自己的类来一起跟踪它们。在 Java 16+ 中,使用 record 来定义该类。您可以在本地、嵌套或单独定义记录。

record Response( Instant start,Duration duration ) {}

定义一个列表并填充。

List< Response > reponses = new ArrayList<>() ;
…
responses.add( new Response( start,d ) ) ;

您可以添加更多成员字段来跟踪用户对每个问题的回答,并标记正确与否。

record Response( int answer,boolean correct,Instant start,Duration duration ) {}
,

Jens 是对的。您应该使用 Java Time API。我建议查看 LocalTimeDuration。对于每个问题,您可以使用以下内容来计算持续时间:

LocalTime questionOneStart = LocalTime.now();
one = scan.next();
LocalTime questionOneEnd = LocalTime.now();
Duration questionOneDuration = Duration.between(questionOneStart,questionOneEnd);

此外,使用 LocalTime 可以让您准确说出用户回答问题的时间。我会在你的情况下使用 LocalTime#format(java.time.format.DateTimeFormatter)

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mmaa");
String answerTimeString = questionOneEnd.format(formatter);

要打印用户回答问题所用的时间,您可以使用 Duration#getSeconds。您还可以根据需要使用 toDaystoHourstoMinutestoMillistoNanos

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res