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

如何在java中为测验创建计时器,java,timer,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

我是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
}
我所需要做的就是找到一种方法来限定这个问题的时间。
谢谢

检查收到问题答案前后的时间

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.");
}

使用java.util.Timer类。我需要的是在2秒钟后停止回答这个问题,如何回答?非常感谢这帮了大忙,非常感谢:)