I've been trying to learn Java using Greenfoot, yet this code always seems to throw a NullPointerException
no matter what I try. I've tried using a pointer, not using a pointer, and even changing the scope, and nothing works.
The code looks like this.
import java.util.*;
import greenfoot.*;
/**
*
*/
public class TurtleActor extends Actor
{
public MouseInfo mouse = Greenfoot.getMouseInfo();
/**
* Act - do whatever the turtle wants to do. This method is called whenever the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
setLocation(mouse.getX(), 100);
}
}
Please help, I cannot tell what is wrong. Either I made a really stupid mistake, or it doesn't work.
You only initialize
mouse
at start-up, but not later.Additionally,
getMouseInfo()
will returnnull
, if the mouse is outside the world boundary.The moment you start the scenario, the mouse is not inside the world. Consequently,
mouse
isnull
.The solution is to call
getMouseInfo()
inact()
, and to check that its result is notnull
before accessing a member method.Please read the documentation.