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

2019/2/2

Problem with Object Interaction

wueschn wueschn

2019/2/2

#
Dear experts Since the new version of Greenfoot 3.53 I have a simple problem. Whenever I try to access an object in the MyWorld class, I get a null pointer exception. I don' t know why because the same thing is working with other older projects ... Could you have a look at my code, I just made a simple interaction This is the MyWorld class, where I generate the objects
import greenfoot.*;  

public class MyWorld extends World
{
    private Bees b;
    private Frogs f;
    private Snakes s; 

    public MyWorld()
    {    
        
        super(600, 400, 1); 
        Bees b = new Bees();
        this.addObject(b, 100, 100);
        Frogs f = new Frogs();
        this.addObject(f, 200, 200);
        Snakes s = new Snakes();
        this.addObject(s, 300, 300);
    }

    public Bees getBees()
    {
        return this.b;
    }

    public Snakes getSnakes()
    {
        return this.s;
    }

    public Frogs getFrogs()
    {
        return this.f;
    }
}
This is another class where I want to use a reference
import greenfoot.*;  


public class Bees extends Actor
{
    
    public void act() 
    {
        if(Greenfoot.mouseClicked(this))
        {
            //this.getWorldOfType(MyWorld.class).getFrogs().move(10);
            MyWorld world = (MyWorld) this.getWorld();
            world.getSnakes().move(10);
            
        }
    }    
}
Thanks for your help wueschn
danpost danpost

2019/2/2

#
Remove the first word in lines 13, 15 and 17. If you create local variables here, the fields declared on lines 5 through 7 will remain null.
wueschn wueschn

2019/2/2

#
.. and that is the error that i get ...
java.lang.NullPointerException at Bees.act(Bees.java:13) at greenfoot.core.Simulation.actActor(Simulation.java:567) at greenfoot.core.Simulation.runOneLoop(Simulation.java:530) at greenfoot.core.Simulation.runContent(Simulation.java:193) at greenfoot.core.Simulation.run(Simulation.java:183)
danpost danpost

2019/2/2

#
danpost wrote...
Remove the first word in lines 13, 15 and 17. If you create declare local variables here, the fields declared on lines 5 through 7 will remain null.
Or, replace with 'this.' at the beginning of those lines.
wueschn wueschn

2019/2/2

#
Thanks a lot, what a silly mistake.
You need to login to post a reply.