简体   繁体   中英

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. 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:

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. The first one should be put outside run() . Also, you need to cancel the timer when the value of score reaches 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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