您好我一直在尝试执行一个java程序计时器,一旦用户键入一个数字,每次都会重置。我试过创建两种方法并停止另一种但无济于事。请发布任何其他可能的解决方案
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
while(true)
{
Scanner reader = new Scanner(System.in);
int a=reader.nextInt();
if(a == 1)
{
Timer timer = new Timer("Printer");
MyTask t = new MyTask();
timer.schedule(t, 0, 1000);
}
else
{
Timer timer = new Timer("Printer");
MyTask t = new MyTask();
timer.schedule(t, 0, 1000);
}
}
}
}
class MyTask extends TimerTask {
//times member represent calling times.
private int times = 0;
public void run() {
times++;
if (times <= 5) {
System.out.println(""+times);
} else {
timer.cancel();
update();
//Stop Timer.
}
}
private void update() {
// TODO Auto-generated method stub
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("Updated timer");
}
};
Timer timer = new Timer();
timer.schedule(timerTask, 1000);
}
}
更新了
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
while(true)
{
int a=reader.nextInt();
Timer timer = new Timer("Printer");
MyTask t = new MyTask();
timer.schedule(t, 0, 1000);
}
}
}
class MyTask extends TimerTask {
//times member represent calling times.
private int times = 0;
public void run() {
times++;
if (times <= 5) {
System.out.println(""+times);
} else {
this.cancel();
//Stop Timer.
}
}
}
更新其工作任何需要改进的地方?
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static Timer timer ;
public static int count = 0;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
while(true)
{
int a=reader.nextInt();
count++;
stop();
}
}
public static void stop()
{
if(count == 1 )
{
timer = new Timer("Printer");
MyTask t = new MyTask();
timer.schedule(t, 0, 1000);
}
else
{
timer.cancel();
timer = new Timer("Printer");
MyTask t = new MyTask();
timer.schedule(t, 0, 1000);
}
}
}
class MyTask extends TimerTask {
//times member represent calling times.
private int times = 0;
public void run() {
times++;
if (times <= 5) {
System.out.println(""+times);
} else {
this.cancel();
//Stop Timer.
}
}
}
答案 0 :(得分:1)
您的代码存在很多问题,包括: