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

2016/9/21

Null Pointer Exception

ymym ymym

2016/9/21

#
if (meetsPinga= true){ getWorld().setBackground(goals); getWorld().removeObject(this); getWorld().removeObjects(getWorld().getObjects(pinga.class)); getWorld().removeObjects(getWorld().getObjects(Ground.class)); getWorld().removeObjects(getWorld().getObjects(goal.class)); getWorld().removeObjects(getWorld().getObjects(Cloud.class)); } private boolean meetsPinga(){ return (getX()>710); } When the object (Penguin) does 'meetsPinga', only Penguin ('this') is removed and I get an error saying java.lang.NullPointerException.
danpost danpost

2016/9/21

#
ymym wrote...
When the object (Penguin) does 'meetsPinga', only Penguin ('this') is removed and I get an error saying java.lang.NullPointerException.
Well, if 'this' is removed from the world, then 'getWorld' will then return 'null' -- and you cannot remove objects from a 'null' world. Remove 'this' last.
ymym ymym

2016/9/24

#
thank you so much it worked! could you explain why 'getWorld' returns 'null' when 'this' is removed though? I'm fairly new to Greenfoot.
danpost danpost

2016/9/24

#
ymym wrote...
could you explain why 'getWorld' returns 'null' when 'this' is removed though? I'm fairly new to Greenfoot.
When you remove 'this' from the world, then 'this' will not be in any world. Therefore, calling 'getWorld' on 'this' actor will return the world that actor is in. If it is not currently in any world, 'null' is returned. Maybe it would help to explain that:
1
World world = getWorld();
is equivalent to:
1
World world = this.getWorld();
So, if 'this' is removed from the world, 'this.getWorld', which returns the world the actor is in, cannot return a World object; therefore, 'null' is returned.
You need to login to post a reply.