问题描述
该程序
我的程序会问三个数学问题,例如10 + 5?
它一次在控制台上显示一个问题。
用户通过命令行回答,并有5秒钟的回答时间 。
下一个问题仅在用户正确回答问题或时间到时显示。
一旦用户在给定时间内正确回答了问题,就需要显示下一个问题(不要等到时间到了)。 当用户回答错误的问题时,计时器应继续运行,并且不应重新启动 。 仅在显示下一个问题时,计时器才会重新启动。
问题所在
用户正确回答问题后,程序不会立即取消计时器。
同样,即使时间到了,下一个问题也不会出现。
用户必须输入一些内容才能继续下一个问题。
最后,当用户输入错误答案时,还会显示下一个问题。
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Random;
/**
*Simple count down timer demo of java.util.Timer facility.
*/
/*
* start timer
* cancel when isLastMoveValid == true
* start timer again soon
* */
public class Countdown {
public static double i = 5;
public static int answer;
static Scanner inputs = new Scanner(System.in);
static Random rand = new Random();
static int num1;
static int num2;
static int questionNo = 3;
public static void main(String args[]) {
while (questionNo >0) {
num1 = rand.nextInt(11);
num2 = rand.nextInt(11);
callTimer();
System.out.println(num1+ "+" + num2 + "?");
answer = inputs.nextInt();
}
} // end of main method
public static void callTimer() {
final Timer timer = new Timer();
i = 6;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
i -= 0.001;
if (i< 0 || answer == num1 + num2) {
questionNo--;
timer.cancel();
}
} // end of run
}, 0, 1); // end of scheduleAtFixedRate
} // end of callTimer
}
1楼
您需要将您的计时器对象作为一个字段 ,以便您可以随时访问它。 请参见cancel方法如何取消。 如果要重新启动计时器,则必须创建计时器和timertask的新对象,因为它们会被线程丢弃。
请参阅有关Timer.cancel方法的文档:
终止此计时器,丢弃任何当前计划的任务。不干扰当前正在执行的任务(如果存在)。一旦计时器终止,其执行线程就会正常终止,并且无法在其上安排更多任务。
例如这样的事情:
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest
{
private Timer timer;
public void cancelTimer()
{
this.timer.cancel();
System.out.println("Canceled timer!");
}
public void startTimer()
{
// once a timertask is canceled, you can not restart it
// because the thread is deleted. So we need to create a
// new object of a timer and a timertask.
TimerTask timerTask = new TimerTask()
{
@Override
public void run()
{
System.out.println("Hello there!");
}
};
this.timer = new Timer();
System.out.println("Starting timer ...");
int period = 1000;
this.timer.schedule(timerTask, 0, period);
}
public static void main(String[] args) throws InterruptedException
{
TimerTest tt = new TimerTest();
tt.startTimer();
Thread.sleep(5000);
tt.cancelTimer(); // you can call this method, as soon as u have a correct answer
Thread.sleep(1000);
tt.startTimer(); // you can restart your timer as demanded
Thread.sleep(5000);
tt.cancelTimer(); // and cancel it again
}
}