簡體   English   中英

為什么我的計時器沒有每秒打印一次?

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

我想制作一個每秒打印一次的代碼,該代碼在我的計時器中傳遞總共 30 秒(因此我制作了一個 for 循環)但是它只是重復打印 1,所以我猜測我的 for 循環不起作用並且它沒有將 1 附加到變量分數。 關於我應該做什么的任何建議? 謝謝。

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

它打印1的原因是您在for循環中放置了以下兩個語句:

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

第一個是在每次迭代中重置score ,而第二個是在每次迭代中打印更新的score值。 第一個應該放在run()之外。 另外,當score的值達到30時,您需要取消計時器。

以下是更新后的代碼:

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:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM