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

2016/4/20

Assigning names

tRapkIng tRapkIng

2016/4/20

#
How could I assign a name to 5 different characters of a game in order to have their name pop up when the reach the finish line?
danpost danpost

2016/4/20

#
tRapkIng wrote...
How could I assign a name to 5 different characters of a game in order to have their name pop up when the reach the finish line?
If you do not already have one, add a subclass of Actor called Racer (or something like that) and have each of your 5 character classes subclass this class. Add an private instance String field to the class so each subclass can assign a name to it in their constructors. Then add public getter and setter methods to the new class so the subclasses can set the value and the pop-up can get the value. Now see if you can get the pop up to show who won. If you then have problems, post the code you tried and we shall see what we can do.
tRapkIng tRapkIng

2016/4/20

#
private string name() { } is this the type of private string I should be using? I only have one actor subclass but they are all assigned by a different number. Ex: person1, person2, etc... so how could i assign different names from person to person?
Super_Hippo Super_Hippo

2016/4/20

#
What you posted is a method. It should be a field/variable:
1
2
3
4
5
6
private String name;
 
public Racer(String racerName)
{
    name = racerName;
}
danpost danpost

2016/4/20

#
Actually, lines 3 through 6 are not needed. Each subclass will have something like this, for example:
1
2
3
4
5
6
7
public class RacerOne extends Racer
{
    public RacerOne()
    {
        name = "Racer One";
    }
}
Come to think about it, the field is not really needed (as well as the intermediate 'Racer' superclass). You can use the class name to determine the winner:
1
String name = winner.getClass().getName();
Of course, with a 'getter' method for the field in the Racer class Super_Hippo suggested, you would not need but one class for all the racers (the 'Racer' class).
You need to login to post a reply.