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

2015/11/4

java.lang.NullPointerException and help with class arrays

CodeShark CodeShark

2015/11/4

#
Hello, I have problems with creating class arrays and with this error. Here is my code :
public class LineWorld extends World
{
    Linep1[] line1 = new Linep1[5000];
    Linep2 line2 = new Linep2();
    static final int x = 500;
    static final int y = 300;
    int dir1 = 0;
    int dir2 = 0;
    public LineWorld()
    {    

        super(x, y, 2);
        Greenfoot.setSpeed(50);
        addObject(new Linep1(), Greenfoot.getRandomNumber(x-30), Greenfoot.getRandomNumber(y-30));
        addObject(line2, Greenfoot.getRandomNumber(x-30), Greenfoot.getRandomNumber(y-30));
        Line1main();
    }


    
    public void Line1main()
    {
        if(Greenfoot.isKeyDown("right")) dir1+=8;
        if(Greenfoot.isKeyDown("left")) dir1-=8;
        line1[0].move(1);
        line1[0].setRotation(dir1);
       
       for(int i=0;i < 5000; i++) 
       {
           addObject(line1[i], (line1[0].getX()), line1[0].getY());
       }
    }
java.lang.NullPointerException is at
        line1[0].move(1);
What I want to do : - a 2 player "line" game My problem : - Line1 class is not allowed to touch itself, but it touchs itself as soon as I create a new object of the class Please help me :)
danpost danpost

2015/11/5

#
For one thing, you are trying to 'move' or 'setRotation' of an element of the array before you are adding any line objects into the world (lines 28 through 31). Another thing is that the array is never filled with any Linep1 objects; the array is declared to hold up to 5000 of them, but none are ever created and set to any elements of that array.
You need to login to post a reply.