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

2013/11/5

Problem with boolean

JasonZhu JasonZhu

2013/11/5

#
public class Ant extends Creature
{

    private boolean canCarryFood = true;

    /**
     * Create an ant with a given home hill. The initial speed is zero (not moving).
     */
    public Ant(AntHill home)
    {
        setHomeHill(home);
    }

    /**
     * Do what an ant's gotta do.
     */
    public void act()
    {
        searchFood();     
        if (canCarryFood = false){
            walkTowardsHome();
        }            
    }
    
    private boolean canCarryingFood()
    {
        return canCarryFood;
    }
    
    private void searchFood()
    {
        Food food = (Food)getOneIntersectingObject(Food.class);
        randomWalk();        
        if (food != null && canCarryFood){
            canCarryFood = false;  
            this.setImage("ant-with-food.gif");            
            food.updateImage();
            food.lostFood();
        }       
    }
    
}
I am having trouble with my ants. When they first spawn from the AntHill, they should have the Boolean canCarryFood as true as I have defined it at the start, however it's not doing that, but rather it's starting out as false. As a result, the Ants aren't picking up any food when they walk over it. I'm stumped on this; does anyone know the problem or fix? Thanks in advance.
danpost danpost

2013/11/5

#
You are using the 'set to equal' symbol on line 20, where you need the 'check for equality' symbol there. A single equal sign will set the evaluated expression on the right to the field on the left, where a double equal sign will compare the two sides for equality.
JasonZhu JasonZhu

2013/11/5

#
Oh heavens, thanks so much. My coding life is just mixed with so many little mistakes.
You need to login to post a reply.