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

2017/3/12

Null Pointer Exception?

SeaShore SeaShore

2017/3/12

#
I'm receiving a run time error called "java.lang.NullPointerException" I'm not really sure what I've done wrong or how I can fix it. The error window pointed out some lines in my code, which I'll write below. I'm making a quiz where you drag buttons with the answers on them to the correct spot on the screen. I thought it would be most efficient to have a button superclass that held the methods each button will use and the common variables they share.
public class MyWorld extends World
{    
    /**
     * Constructor for objects of class MyWorld.
     * 
     */
    public MyWorld()
    {   
          createAnswerBank();      
    }   
    
    /**
     * Create a list of formulas to fill the answer bank.
     */
    private void createAnswerBank()
    {
        int x = 7*getWidth()/8;
        int y = 14*getHeight()/125;
        int z = 7*getHeight()/125;
       
       One one = new One();
       addObject(one, x, y+z*Greenfoot.getRandomNumber(16));
    }
}

public class Button extends Actor
{
    public int intialHeight = world.getHeight()/10;
}

public class One extends Button
{
    public void act() 
    {
        checkAnswer(intialHeight);       
    }  
Super_Hippo Super_Hippo

2017/3/12

#
What is 'world' in line 28?
danpost danpost

2017/3/12

#
The button class should be:
public class Button extends Actor
{
    public int intialHeight;

    protected void addedToWorld(World world)
    {
        intialHeight = world.getHeight()/10;
    }
}
When an object is created (example: a Button object), the first thing that happens is that memory is allocated for all the fields that object is to maintain (example: intialHeight, as well as world, rotation, x, y and image from the Actor class); if the fields have any initial values set to them, this is when that will happen. However, the initial value of 'world' is 'null' at that time -- the object has not yet been added into any world -- and as you cannot call a method on a 'null' value, you get the NullPointerException error. The addedToWorld method is an Actor class method that is automatically called when the actor is added into any world. This is the first place you can acquire any information about any world (usually only that world which it is placed into).
SeaShore SeaShore

2017/3/13

#
Thank you danpost!
You need to login to post a reply.