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

2013/2/15

getObjectsInRange Method not working...

postamt postamt

2013/2/15

#
Hi all, we just have started Greenfoot Java programming in school and I have a question regarding the getObjectsInRange Method: When a crab notices a Lobster in its range I want the crab to move away from the Lobster, so I created a class called Instinct where I have methods about animals behaviors. On of them is avoid:
    public void avoid(java.lang.Class clss)
    {
        java.util.List actors = getObjectsInRange(50,clss);
        if (actors.contains(clss))
        {
            turn(45);
        }
    }
In the Crab class I use the avoid Method and call it like this: avoid(Lobster.class); But when the Crab moves to the Lobster it doesn't turn. Why? Would be nice, if anyone can help me out ;) Best, Postamt
danpost danpost

2013/2/15

#
Any and all objects returned from the use of 'getObjectsInRange' are returned as Object class objects. In your case, since you are already looking for Lobster.class objects, anything returned will be Lobster objects returned as Object class objects. If the list is not empty, then 'actors' will contain at least one object that can be cast to the Lobster class (in fact, all the objects in the list will be castable to the Lobster class). Change your 'avoid' method to:
public void avoid(Class clss)
{
    if (!getObjectsInRange(50, clss).isEmpty())
    {
        turn(45);
    }
}
By not creating a reference to a List object, importing java.util.List is not neccessary for this method.
postamt postamt

2013/2/15

#
Thanks! Now it works. I also understand your code and I understand why I don't need the List. But what I don't get is why it isn't working. I mean the List contains Lobster objects and it should also work or not? Thanks again for your quick help ;)
danpost danpost

2013/2/15

#
The reason it did not work is because you were asking for a 'Class' in the list, not an 'Object'. 'actors' will contain a list of objects created from the specified class, not the classes themselves.
You need to login to post a reply.