Search code examples
javagreenfoot

Greenfoot Counter minus one


Hi i'm trying to decrease the counter with 1 in the public void minScore

score++ adds the counter with 1 what is the equivalent to decrease the counter with 1 ?

public class Counter  extends Actor
{
    private int score = 0;

    public void act()
    {
        setImage(new GreenfootImage("Score : 0" + score, 24, Color.WHITE, Color.BLUE));
    }

    /**
     * Increase the total amount displayed on the counter, by a given amount.
     */
    public void addScore()
    {
        score++;
    }

    public void minScore()
    {
        score++;
    }

}

Solution

  • You may use score-- (return old value and decrease this value) or --score (decrease this value and return updated value) to decrease your counter.

    I advice you to write methods that returns value, like:

    public int decrementAndGet() {
        return --score;
    }
    
    public int getAndDecrement() {
        return score--;
    }
    

    By analogy with names of methods in atomic classes.