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

2013/6/28

Help with greenfoot

darokrithia darokrithia

2013/6/28

#
I am making a program/simulation which builds of of the basic wombat program. Wombats are smarter and reproduce and die, it also implements a predator aspect. The predators located the prey fine, but when I tried to fix a bug (and no I am stupid and did not save the pre-bug fix code), I get an error about prey (a wombat) and (A list of wombats called) wombatsNearby.get(0) I get incompatible types error. Here is more code: private void newPrey(){ int distance = 480; boolean done = false; List wombatsNearby; while ((distance <480) && (done = false)){ wombatsNearby = (getNeighbours(distance, false, Wombat.class)); if (wombatsNearby.isEmpty()){ distance++; } else{ done = true; } } wombatsNearby = getNeighbours(distance, false, Wombat.class); if(done = true){ prey = wombatsNearby.get(0); } else{ prey = null; } } If I am unclear, just tell me
Zamoht Zamoht

2013/6/29

#
It's because wombatsNearby.get(0); returns an object of type Object. To fix this you can typecast the method call: prey = (Wombat)wombatsNearby.get(0); This will make wombatsNearby.get(0); return an object of type Wombat instead.
danpost danpost

2013/6/29

#
The main problem is in the line:
if (done = true)
'done = true' will set 'done' to 'true' and the 'if' condition will always return 'true'. What you want is to use the equality operator '==' (or no operator because the value of 'done' is already a boolean):
if (done == true)
// or
if (done)
Use of the list iterator 'for' could be used to drastically simplify the 'newPrey' method:
private void newPrey()
{
    prey = null;
    int closest = 480;
    for (Actor actor: getNeighbours(480, false, Wombat.class))
    {
        int far = Math.hypot(actor.getX()-getX(), actor.getY()-getY());
        if (far < closest)
        {
            closest = far;
            prey = actor;
        }
    }
}
You need to login to post a reply.