NullPointerException for Seemingly no reason

59 Views Asked by At

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.

1

There are 1 best solutions below

0
On

You only initialize mouse at start-up, but not later.

Additionally, getMouseInfo() will return null, if the mouse is outside the world boundary.

The moment you start the scenario, the mouse is not inside the world. Consequently, mouse is null.

The solution is to call getMouseInfo() in act(), and to check that its result is not null before accessing a member method.

Please read the documentation.