ScottPretorius
ScottPretorius

Reputation: 1

Adding to a variable in a timer

I'm a beginner with java so sorry for the basic question. I'm trying to add 5 to a variable every minute, but I cannot manage to do it without a scope-problem or without the addition failing to work. How to fix this?

My code is:

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

public class MainTimer {
    public static void main(String[] args) {


        Timer sigMassTimer = new Timer();

        int sigMass;
        sigMass = 0;

        sigMassTimer.schedule(new TimerTask(){

            @Override
            public void run(){

                String invSigMass = "You have "+ (sigMass + 5) + " units.";
                System.out.println(invSigMass);
            }
        }, 1*60*1000, 1*60*1000);       
    }   
}

and I get "You have 5 units" as output every minute.

Upvotes: 0

Views: 1112

Answers (2)

qqilihq
qqilihq

Reputation: 11474

You need to move the sigMass declaration into the TimerTask (else wise you can only access it, if it is declared final and thus cannot be incremented with each invocation) and change the way you increment:

Timer sigMassTimer = new Timer();
sigMassTimer.schedule(new TimerTask() {
    int sigMass = 0;
    @Override
    public void run() {
        sigMass += 5;
        String invSigMass = "You have " + sigMass + " units.";
        System.out.println(invSigMass);
    }
}, 1*60*1000, 1*60*1000);
// Output:
// You have 5 units.
// You have 10 units.
// You have 15 units.
// You have 20 units.
// You have 25 units.

Alternatively, you could also make sigMass a static member of your MainTimer class.

Upvotes: 1

lagboy
lagboy

Reputation: 94

sigMass is initialized to 0, and you're just displaying sigMass + 5, that is 5 every minute instead of actually incrementing 5 to sigMass.

Try changing this bit:

String invSigMass = "You have "+ (sigMass + 5) + " units.";

to

sigMass = sigMass + 5;    
String invSigMass = "You have "+ sigMass + " units.";

Tell me if it works.

Upvotes: 0

Related Questions