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

2020/4/3

I am supposed to create a method that detects the nearest object (minnow) to another object (shark). The code seems to have some errors, but I am not able to compile it.

Atharva1912 Atharva1912

2020/4/3

#
public Minnow nearestMinnow()
    {
        int diff = 1000000;
        Minnow nearest = null;
        for (Actor minnow: getWorld().getObjects(Minnow.class))
        {
          int D = (int) distanceTo(minnow);
          if (D < diff)
          {
              diff = D;
              nearest = minnow;
            }
        }
         return minnow;
    }
the error that is shown is "incompatible types: sofia.micro.Actor cannot be converted to Minnow"
danpost danpost

2020/4/3

#
minnow is of type Actor but, nearest is of type Minnow. You need to typecast minnow as type Minnow in order to set it to nearest. That is, line 13 needs to be as follows:
nearest = (Minnow)minnow;
Also, your method is supposed to return the nearest minnow; not the last one in the list.
You need to login to post a reply.