如何在java中为测验创建计时器

时间:2018-05-31 15:41:44

标签: java timer

我是Java的初学者,正在开展一个测验的学校项目。 我想在我的代码中插入一个计时器,这样问题只能回答2秒,然后答案就算错了,我们继续讨论下一个问题。任何帮助将不胜感激:)提前感谢。 我需要的是阻止问题在2秒后回答,怎么样?

这是代码

acr = "ASCII"; //this is where i store the acronym for it to be outputted
System.out.println(acr); //this is where i output the acronym
String ans = Keyboard.readString(); //class that reads the keyboard and stores the output in string variable ans
if (ans.equalsIgnoreCase("American Standard Code For Information Exchange")) //tests if answer is correct
{
    System.out.println("Correct answer");//if the answer is correct it outputs correct
    right++;// this is irrelevant
} else {
    System.out.println("Wrong Answer - American Standard Code For Information Exchange"); //if the answer is wrong it outputs wrong answer and gives you the correct meaning
    wrong++; //this is also irrelevant
}

我需要的是找到一种方法来为问题设定时间限制。 感谢

1 个答案:

答案 0 :(得分:0)

检查问题答案前后的时间。

System.out.println(acr);
long start = System.nanoTime();
String ans = Keyboard.readString();
long stop = System.nanoTime();
double seconds = (stop - start) / 1_000_000_000.0;
if (seconds > 2.0) {
    System.out.println("Sorry, too slow.");
} else if (ans.equals(expected)) {
    System.out.println("Correct!");
} else {
    System.out.println("Wrong. Better luck next time.");
}