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

2016/9/13

How do I get access to a variable in another class?

TheFischy TheFischy

2016/9/13

#
I have an integer "score" defined in the class Player. How do I get this integer in another class?
Super_Hippo Super_Hippo

2016/9/13

#
If it is a private int, then you need a getter method:
1
2
3
4
public int getScore()
{
    return score;
}
If there is only one Player object in the world, then you can get the score in another class like this:
1
2
3
4
5
//in an Actor subclass in the same world
int playerScore = ((Player)(getWorld().getObjects(Player.class).get(0)).getScore();
 
//in the World subclass in which the player is in
int playerScore = ((Player)(getObjects(Player.class).get(0)).getScore();
TheFischy TheFischy

2016/9/14

#
Thank you for your quick reply. I need int "score" in the class "ScoreBoard". So I copied your code and put
1
2
3
4
public int getScore()
{
    return score;
}
into the class "Player". Then I put
1
2
//in an Actor subclass in the same world
int playerScore = ((Player)(getWorld().getObjects(Player.class).get(0)).getScore();
into the class "ScoreBoard", and
1
2
//in the World subclass in which the player is in
int playerScore = ((Player)(getObjects(Player.class).get(0)).getScore();
into the World subclass ("MyWorld" in this case). So Greenfoot says that at the end of your code a ")" is missing, so it should be ".getScore())". But then these brackets get underlined and the error report says: "incompatible types: int cannot be converted to Player." What can I do?
Super_Hippo Super_Hippo

2016/9/14

#
The ) is missing after the get(0)), another ) has to be added after that. The code was an example what you have to do to get the value of the score field. The line itself doesn't do anything.
danpost danpost

2016/9/14

#
Super_Hippo wrote...
The ) is missing after the get(0)), another ) has to be added after that. The code was an example what you have to do to get the value of the score field. The line itself doesn't do anything.
Actually, you could say there is an extra ( after (Player) in both given lines that should be removed.
You need to login to post a reply.