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

2021/1/13

Referencing int from World to Actor - NullPointerException

Suavessence Suavessence

2021/1/13

#
Hello, I am trying to reference the Space world "time" int from the PointOrbs Actor class. I have attempted to use a getTime() function within the PointOrbs constructor, but am getting a null pointer exception once the program attempts to create a PointOrbs object. The objective is to set the speed of the orbs according to a fraction of time. Here is the Space class:
import greenfoot.*;
public class Space extends World
{
	private int time;

	public Space()
	{    
        	GreenfootImage background = getBackground();
        	background.setColor(Color.BLACK);
        	background.fill();
        	prepare();
        	time = 0;
    	}

	public void act()
    	{
        	countTime();
        	if (Greenfoot.getRandomNumber(1000) < 2)
       		{
            		addObject(new PointOrbs(), Greenfoot.getRandomNumber(460), -60);
        	}
	}

	public int getTime()
   	{
		return time;
   	}

	private void countTime()
	{
        	if (lives != 0)
        	{
            		time++;
        	}
	}
}
Here is the PointOrbs class:
import greenfoot.*;  
public class PointOrbs extends Actor
{
    private int speed;

    public PointOrbs()
    {
        Space space = (Space)getWorld();
        speed = 1 + (space.getTime()/100);
    }
    
    public void act() 
    {
        setLocation(getX(), getY()+speed);
        turn(1);
        
        if (getY() == 599) 
        {
            Space space = (Space)getWorld();
            space.removeObject(this);
        }
    }   
}
Here is the error: java.lang.NullPointerException at PointOrbs.<init>(PointOrbs.java:9) at Space.act(Space.java:20) at greenfoot.core.Simulation.actWorld(Simulation.java:573) at greenfoot.core.Simulation.runOneLoop(Simulation.java:506) at greenfoot.core.Simulation.runContent(Simulation.java:193) at greenfoot.core.Simulation.run(Simulation.java:183)
danpost danpost

2021/1/13

#
Suavessence wrote...
I am trying to reference the Space world "time" int from the PointOrbs Actor class. I have attempted to use a getTime() function within the PointOrbs constructor, but am getting a null pointer exception once the program attempts to create a PointOrbs object.
In PointOrbs class, change line 6 to be:
protected void addedToWorld(World world)
The actor must be in a world for getWorld to return a World object instead of null (the actor is not in any world during its creation -- or, while being constructed). You could also change line 8 to be:
Space space = (Space) world;
since you now already have a local reference to the world it is placed in.
You need to login to post a reply.