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

2017/3/21

Returning the Nearest Object

rockon411 rockon411

2017/3/21

#
I need to return the nearest object in the world using a for loop. When there are no objects it should return null. I have a method distanceTo(Actor actor) that is able to calculate the distance to a certain object. I have googled and I cannot seem to get something that works for me. I need help!
Super_Hippo Super_Hippo

2017/3/21

#
Maybe that works for you:
private Actor getNearestObject()
{
    int diff = 1000000; Actor nearest = null;
    for (Actor a : getWorld().getObjects(ClassName.class))
    {
        int d = diff = (int) Math.sqrt(Math.pow(getX()-a.getX(),2)+Math.pow(getY()-a.getY(),2));
        if (d < diff)
        {
            diff = d;
            nearest = a;
        }
    }
    return nearest;
}
rockon411 rockon411

2017/3/21

#
Greenfoot highlights the "return nearest;" lines and gives me the error incompatible types - found.sofia.micro.Actor but expected Minnow. Minnow is my class FYI.
Super_Hippo Super_Hippo

2017/3/21

#
sofia micro actor? Please show what you have changed.
rockon411 rockon411

2017/3/21

#
public Minnow nearestMinnow()
    {
        int diff = 1000000; 
        Actor nearest = null;
        for (Actor minnow : getWorld().getObjects(Minnow.class))
        {
            int d = diff = (int) distanceTo(minnow);
            if (d < diff)
            {
                diff = d;
                nearest = minnow;
            }
        }
            return nearest;
    }
this is what i have
Super_Hippo Super_Hippo

2017/3/21

#
Since you changed the 'Actor' in line 1, you also have to change the ones in line 4 and 5 (or change line 1 back). Oh and you have to remove the '= diff' in line 7... I messed this up.
int d = (int) distanceTo(minnow);
rockon411 rockon411

2017/3/21

#
public void testNearestMinnow2()
    {
        Minnow dory = new Minnow();
        Minnow nemo = new Minnow();
        ocean.add(dory, 50, 51);
        ocean.add(shark, 50, 50);
        ocean.add(nemo, 100, 100);

        assertEquals(dory, shark.nearestMinnow());
    }
It compiles, but I am still having issues getting the test to pass. The nearestMinnow() keeps returning null.
Super_Hippo Super_Hippo

2017/3/21

#
I am not sure how this code is related to the nearestMinnow method. Did you see that I edited my post referring to line 7?
rockon411 rockon411

2017/3/21

#
Actually I didn't and I just fixed it! Everything compiles and the tests pass. Thank you so much!
You need to login to post a reply.