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

2012/10/9

Passing variables

tomduff5985 tomduff5985

2012/10/9

#
I need to make a score variable in one actor pass and be updated by another actor. I know I am using the constructor wrong. Can anyone help? Here is the code for the first actor: public class Fisherman extends Animal { protected int score = 0; public int setScore() { score = ++; return score; } which is called by the second actor: if (canSee(Fish.class)) { eat(Fish.class); setScore(); fishCount --; any thoughts?
danpost danpost

2012/10/9

#
First 'score = ++;' is not a valid statement. You probably wanted 'score++;'. Now, you are calling 'setScore();' from the second actor; however, you are not doing anything with the returned value. Hence, it is lost. Change 'setScore();' to 'int newScore = setScore();' and 'newScore' will hold the new score value in the calling class (only until the method is done executing; to save the score longer, you need to create an instance int field in the class and store it there).
tomduff5985 tomduff5985

2012/10/10

#
The problem now is that it is only holding initial value (0) and never updating again.
danpost danpost

2012/10/10

#
If you only have one fisherman in the world, then in the second actor's class, add the following method:
public void setScore()
{
    if (getWorld().getObjects(Fisherman.class).isEmpty()) return;
    Fisherman man = (Fisherman) getWorld().getObjects(Fisherman.class).get(0);
    man.setScore();
}
You need to login to post a reply.