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

2015/3/19

Add to counter when object gets removed

GuilhermeGomes GuilhermeGomes

2015/3/19

#
Hello everyone. I'm trying to program a counter that, everytime a bird gets to the edge of the world (runs away) , decreases one value to it. But when the bird gets to the edge and its removed it gives me NullPointerException. Any help? BirdWorld
public BirdWorld()
    { 
        super(1000, 600, 1);        
        BirdCounter birdcounter = new BirdCounter();
        addObject(birdcounter, 120, 57);
}
//
//
//
    public void subScore()
    {
      birdcounter.subtractCount();  
    }
BirdCounter
public class BirdCounter extends Actor
{
    private int birdCount = 10;
    public BirdCounter()
    {
        setImage(new GreenfootImage(200,30));
        update();
    }
    
    public void subtractCount()
    {
        birdCount--;
        update();
    }
    
    public void update()
    {
        GreenfootImage img = getImage();
        img.clear();
        img.setColor(Color.BLACK);
        img.drawString("Pássaros:" + birdCount,4,20);
    }
}
The Bird
    public void act() 
    {
        BirdWorld mybirdworld = (BirdWorld) getWorld();
        move(2);
        if(atWorldEdge())
        {
            //getWorld().removeObject(this); i comment this to try to fix with turn
            turn(180);
            mybirdworld.subScore();           
        }
    }
danpost danpost

2015/3/19

#
In line 4 of the BirdWorld code above, you are creating a local variable called 'birdcounter' and assigning it the BirdCounter object. This local variable is not your instance field called 'birdcounter', which continues to be un-assigned (or 'null').
GuilhermeGomes GuilhermeGomes

2015/3/20

#
I earlier forgot to write this
public class BirdWorld extends World
{
    private BirdCounter birdcounter;
. So how do i do it? I followed Joy of Code #28 guide so i tried to do the same has michael EDIT: IT WORKS NOW :D!!! only had to change to this
birdcounter = new BirdCounter();
        addObject(birdcounter, 120, 57);
thank you for your help!
You need to login to post a reply.