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

2017/10/25

Null pointer exception error

bryanz1345 bryanz1345

2017/10/25

#
hi everyone im trying to use the method getObjects() and store them in a list but i keep getting a null pointer exception the program runs and compiles but as soon as the objects fade from the screen i get a null pointer exception ive attached my class code. i keep getting the error for the line" List<Sigma> sigmas = world.getObjects(Sigma.class);"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
 * A rotating Sigma on the visualizer
 *
 * @author Bryan Oritz
 * @version 1.2
 */
 
public class Sigma extends Actor
{
    int[] xPoints ={37,10,18,10,37};
    int[] yPoints ={10,10,18,30,30};
    int nPoints = 5;
    /**
     *
     */
    public Sigma()
    {
 
    }
     
    /**
     * Sigma constructor
     */
    public Sigma(int width, int height, Color color)
    {
        GreenfootImage image = new GreenfootImage(width, height);
        image.setColor(color);
        image.drawPolygon(xPoints, yPoints, nPoints);
        setImage(image);
    }
     
    /**
     * Act - do whatever the Stars wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        int alpha = getImage().getTransparency();
        if (alpha > 2)
        {
            getImage().setTransparency(alpha - 2);
        }
        else
        {
            getWorld().removeObject(this);
        }
        World world = getWorld();
        List<Sigma> sigmas = world.getObjects(Sigma.class);
        for (Sigma sigma : sigmas)
        {
            turn(5);
        }
    }   
}
danpost danpost

2017/10/25

#
The problem is that when line 47 removes a Sigma object from the world, the 'getWorld' used on line 49 will return 'null' (the 'act' method is still executing on 'this' Sigma object)). Two ways you can avoid the errror are (1) add a 'return;' statement immediately after the statement removing the actor from the world; and, (2) move lines 49 through 54 to the beginning of the 'act' method ensuring that the actor is in the world when 'getWorld' is called.
bryanz1345 bryanz1345

2017/10/26

#
Hey danpost! thank you for the quick reply , moving lines 49 - 54 was a super simple solution thank you for your help it was greatly appreciated!
You need to login to post a reply.