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

2015/11/11

Turning towards objects

hoothoot hoothoot

2015/11/11

#
why won't this code work?
public void move()
    {
        Car car = (Car) getWorld().getObjects(Car.class);
        turnTowards(car.getX(), car.getY());
        move(1);
    }
hoothoot hoothoot

2015/11/11

#
the error message is java.lang.ClassCastException: java.util.ArrayList cannot be cast to Car
davmac davmac

2015/11/11

#
The error message is right; an ArrayList is not a Car, so the cast is invalid. You are calling a method which returns a list (getWorld().getObjects(...)). You can't just cast it to a Car. You need to get an item from the list, and cast that to Car. If you know there will always be at least one Car in the world, you can write:
public void move()
    {
        Car car = (Car) getWorld().getObjects(Car.class).get(0);
        turnTowards(car.getX(), car.getY());
        move(1);
    }
(Or, use Greenfoot 3, and then you can use the same code but the cast is no longer necessary).
hoothoot hoothoot

2015/11/11

#
thanks
You need to login to post a reply.