[英]how to stop a timer with an if statement
I'm trying to stop a timer that ticks down from ten seconds to zero. 我正在尝试停止一个计时器,该计时器的时间间隔从十秒降至零。 The problem is that the finish method only returns the first tick, rather than counting all the numbers down to one. 问题在于,finish方法仅返回第一个刻度,而没有将所有数字倒计数为一个。 How can I make a boolean method return a value for every second rather than just the first? 如何使布尔方法每秒返回一个值,而不仅仅是第一个?
import java.util.Timer;
import java.util.TimerTask;
public class Countdown {
static int interval;
static Timer timer;
boolean off;
public Countdown() {
int seconds = 10;
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = seconds;
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private int setInterval() {
off = false;
if (interval == 1){
timer.cancel();
off = true;
return --interval;
}else{
off = false;
return --interval;
}
}
public boolean finish(){
return off;
}
}
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public static void main(String[] args){
Countdown countDown = new Countdown();
countDown.finish()
System.out.println(countDown.finish);
if(countDown.finish() == true){
System.out.println("works");
}
}
If you want to write the value of finish
every second, you should design your code to print it ever second, not just on startup... 如果要每秒写一次finish
的值,则应该设计代码以每秒打印一次,而不仅仅是在启动时...
ATM finish
is only printed in the main-method and nowhere else. ATM finish
仅在主方法中进行印刷,而在其他任何地方均不印刷。 Move that line into the Runnable
used by the Timer
and it should print as expected. 将该行移到Timer
使用的Runnable
,它应该按预期进行打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.