SvanSomeren
SvanSomeren

Reputation: 55

Iterate through list using scheduleAtFixedRate in Java

I'm trying to iterate through a list based on a timer which the user can set. However I can't find a good way to do it within the TimerTask runnable.

The general idea can be found in the code I've shared below. Announcements is a List of List<String>. On every interval I want to take the next announcement from announcements and display the strings within it. I've got all of it working except the timer going over multiple announcements:

 timer.scheduleAtFixedRate(new TimerTask() {
        int iterator = 0;
        @Override
        public void run() {

            List<String> announcement = announcements.get(iterator);

            for (String line : announcement) {
                Bukkit.broadcastMessage(line);
            }

            iterator++;
            if(iterator > announcements.size()){
                iterator = 0;
            }
        }
    }, 0, (int)config.get("interval")*1000);

Using the code I posted I get an IndexOutOfBoundsException and it never even posts any of the messages. If I remove the iterator code it will show the first announcement endlessly.

Upvotes: 1

Views: 224

Answers (1)

Ihor Patsian
Ihor Patsian

Reputation: 1298

You have wrong following condition:

if(iterator > announcements.size())

In this case the size of the list is exceeded so IndexOutOfBoundsException is thrown. But the condition should check is the iterator greater or equal to size of list:

if(iterator >= announcements.size())

Upvotes: 2

Related Questions