简体   繁体   English

为什么我的计时器没有每秒打印一次?

[英]Why doesn't my timer print every second that passes?

I wanted to make a code that printed every second that passes in my timer for a total of 30 seconds (hence why I made a for loop) however it just repeatedly prints 1, so I am guessing that my for loop isn't working and it isn't appending 1 to the variable score.我想制作一个每秒打印一次的代码,该代码在我的计时器中传递总共 30 秒(因此我制作了一个 for 循环)但是它只是重复打印 1,所以我猜测我的 for 循环不起作用并且它没有将 1 附加到变量分数。 Any suggestions on what I should do?关于我应该做什么的任何建议? Thanks.谢谢。

public class TimerSchedule {

public static void main(String[] args) {  
    // creating timer task, timer  
    Timer t = new Timer();  
    TimerTask tt = new TimerTask() {  
        @Override  
        public void run() {  
           for(int i=0; i<30;i++)  
            {  
            int score = 0;
            score ++;
            System.out.println(score);
            }  
        };  
    };  
    t.scheduleAtFixedRate(tt,0,1000);    
       }  
    }  

The reason why it is printing 1 is that you have put the following two statements inside the for loop:它打印1的原因是您在for循环中放置了以下两个语句:

int score = 0;
System.out.println(score);

The first one is resetting score in every iteration while the second one prints the updated value of score in each iteration.第一个是在每次迭代中重置score ,而第二个是在每次迭代中打印更新的score值。 The first one should be put outside run() .第一个应该放在run()之外。 Also, you need to cancel the timer when the value of score reaches 30 .另外,当score的值达到30时,您需要取消计时器。

Given below is the updated code:以下是更新后的代码:

import java.util.Timer;
import java.util.TimerTask;

public class Main {
    public static void main(String[] args) {
        Timer t = new Timer();
        TimerTask tt = new TimerTask() {
            int score = 0;

            @Override
            public void run() {
                System.out.println(++score);
                if (score == 30) {
                    t.cancel();
                }
            };
        };
        t.scheduleAtFixedRate(tt, 0, 1000);
    }
}

Output: Output:

1
2
3
...
...
...
29
30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM