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

2019/5/9

Accessing Actor's Instance Variable from a List of Objects Created in a World

MRCampbell MRCampbell

2019/5/9

#
I am trying to remove an object if its "energy" is less then 10. "Energy" is an instance variable of a Creature object. This is a method in my World Class that I hope will accomplish this task. getEnergy() is a method defined in the Creature class that simple returns energy.
1
2
3
4
5
6
7
8
9
10
11
12
13
public void cullHerd()
    {
            List<Object> creaturesToRemove = new ArrayList<Object>();
            creaturesToRemove = getObjects(Creature.class);
            for (int i = 0; i < creaturesToRemove.size(); i = i + 1)
            {
                Actor a = (Actor) creaturesToRemove.get(i);
                if (a.getEnergy() < 10)
                {
                    removeObject(a);
                }
            }
    }
When I run this, I am told:"cannot find symbol - method get energy()" So I tried accessing the method this way:
1
if (Creature.getEnergy() < 10)
and I am told: non-static method getEnergy() cannot be referenced from a static context.
Super_Hippo Super_Hippo

2019/5/9

#
In line 7, change both instances of "Actor" to "Creature". Otherwise, it can't find the method "getEnergy" because it is searching in the Actor class and its superclasses and can't find your method which is in a subclass of Actor.
MRCampbell MRCampbell

2019/5/10

#
Thanks! I was so close.
Super_Hippo Super_Hippo

2019/5/10

#
Btw, you can also do this:
1
2
3
4
for (Creature c : getObjects(Creature.class))
{
    if (c.getEnergy() < 10) removeObject(c);
}
MRCampbell MRCampbell

2019/5/14

#
Ok
1
if (c.getEnergy() < 10) removeObject(c);
is a more consice version of:
1
2
3
4
if (a.getEnergy() < 10)
       {
             removeObject(a);
       }
Correct? And I imported the list package for no reason? Great. Are you telling me your 4 lines replace my code in lines 3 through 12?
Super_Hippo Super_Hippo

2019/5/14

#
Yes and yes.
You need to login to post a reply.