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

2018/1/8

Getting a java.lang.NullPointerException

Dimako21 Dimako21

2018/1/8

#
This only happens sometimes, but after a bullet hits an asteroid it creates Debris. That Debris later has a randomly generated decay and is destroyed after the decay timer is up as seen on line 27 My question to you is why does it only randomly choose to give a NullPointerException and how do I fix it?
import greenfoot.*; 
import java.util.Random;

public class Debris extends Actor
{
    World MyWorld = getWorld();
    Random randomR = new Random();
    private int speed = 0;
    
    int decay;
    public Debris()
    {
        int rotation = randomR.nextInt(360)+1;
        decay = (int) ((Math.random() * 50));
        speed = (int) (1+ Math.random() * 2);
        setRotation(rotation);
    }
    public void act() 
    {
        
        
        move(speed);
        destroyAtEdge();
        if (decay != 0)
        {
            decay--;
        }
        else
        {
            getWorld().removeObject(this);
        }
        
        
    }
    public void destroyAtEdge()
    {
        int y = getY();
        int x = getX();
        World myWorld = getWorld();
        if (y == 0 )
        {
            getWorld().removeObject(this);
        }
        else if ( x==0 )
        {
            getWorld().removeObject(this);
        }
        else if (y == myWorld.getHeight() - 1)  //   -1 because it would not find it otherwise
        {
            getWorld().removeObject(this);
        }
        else if ( x == myWorld.getWidth() - 1)   //   -1 because it would not find it otherwise
        {
            getWorld().removeObject(this);
        }
    }

 
}
Another question I have about the code is the turn / setRotation functions. Whenever the debris is generated, it is given a random rotation and then turned towards it. For some reason it only ends up having 8 or so different rotations visible as shown here And I am wondering if there is anyway I can make it have more possible outcomes. Or is this due to the object being so small? (2x2 pixels) Edit: took out the code for generating sound as that was copied by mistake
danpost danpost

2018/1/9

#
Restriction in directions is due to speed and the hardware makeup of pixels of the screen (cannot be moved between pixels). The null pointer exception is probably due to the debris wanting to time itself out of existence when at an edge. If removed due to edge by line 23, removing due to time (line 30) will error as 'getWorld' will now return a 'null' value.
You need to login to post a reply.