This site requires JavaScript, please enable it in your browser!
Greenfoot back
craigv
craigv wrote ...

2012/1/31

Counters

craigv craigv

2012/1/31

#
is it possible to have an identical counter in different actor classes, but when i add +1 to it, it adds to an overall counter/adds all the the times I add 1 to the counter from the seperate classes?
danpost danpost

2012/1/31

#
I believe the answer to your question is no, BUT, you can have references to the same counter in multiple classes and then, if you change one, all will show the change. So, if you had in your world
Counter counter = null;
and in your world constructor
counter = new Counter();
addObject(counter, xLocation, yLocation);
then in your actor classes, you could put
Counter counter = null;
and then
protected void addedToWorld(World world)
{
    counter = world.counter;
}
Now, the value of the counter, if not private, can be changed anywhere there is a reference to it. Example:
counter.value += 1;
if value is the integer variable that holds the count of the counter.
plcs plcs

2012/1/31

#
If you create a class that contains a static method for getting a value and also another for modifying it you can achieve it. Something like
public class Counter {

private static int counter = 0;

public static int getCounter() {
    return counter;
}

public static void setCounter(int value) {
    counter = value
}

public static void incremementCounter() {
    counter++;
}

}
And in other classes you can call it with;
Counter.getCounter();
And all the other commands, and this would stay consistent across all your classes. Be careful as static variables are not reset from pressing Reset, but rather by hitting the Compile All button again, to wipe its existing value.
You need to login to post a reply.