-2

I have this very simple code:

public class Player{
    private int x,y,velX,velY,width,height,id;
    private boolean isControllable;


    public Player(int _x,int _y,int _width,int _height,int _id,boolean _cont){
        x = _x;
        y = _y;
        width = _width;
        height = _height;
        id = _id;
        isControllable = _cont;
        if(_cont == true){
            addToCont();
        }
    }

    private void addToCont(){
        Main.controllable.add(this);
    }

}

And this:

public class Main {

    public static Render render = new Render();
    public static Controlls controll = new Controlls();

    public static LinkedList<Player> controllable;

    public static void main(String[] args) {
        controllable = new LinkedList<Player>();
        render.height = 750;
        render.width = 1000;
        render.RenderWindow();
    }
}

As You can see I am trying to add this instance of player class to the linked list. But it returns an error:

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at game.Player.Player.addToCont(Player.java:23)
at game.Player.Player.<init>(Player.java:18)
at game.Main.Render.<init>(Render.java:28)
at game.Main.Main.<clinit>(Main.java:9)

What am I doing wrong?

Edu G
  • 1,030
  • 9
  • 23
Ervin
  • 55
  • 1
  • 7
  • Your ``Render`` class instantiates a ``Player`` object which accesses ``Main.controllable`` which is null. – f1sh Feb 20 '17 at 14:44
  • It is not a duplicate, since I know what is a NullPointerExc and i know how to fix it. – Ervin Feb 20 '17 at 14:45
  • 2
    Then why isn't it fixed? – f1sh Feb 20 '17 at 14:46
  • @Ervin, if you would have check, it is null because you build your static instance before you build `controllable`. So this is a duplicate since you could have find the problem by reading the stack trace, you failed during the constructor of `Render` which is done way before the building of the `LinkedList`. **A duplicate is not always exactly the same code... but the same pattern to resolve it** – AxelH Feb 20 '17 at 14:48

1 Answers1

2

controllable is not instantiated. Replace it in Main with:

public static LinkedList<Player> controllable = new LinkedList<>();
tak3shi
  • 2,305
  • 1
  • 20
  • 33
  • 1
    i would also move it few lines up, to be created before Render constructor is called – user902383 Feb 20 '17 at 14:43
  • _not instantiated_ yet ;) this is a nice mix up with static and non static context. – AxelH Feb 20 '17 at 14:44
  • To all people up there, and who maked this quastion as dupplicate: this is the kind of answer I was waiting for! Thak You tak3shi – Ervin Feb 20 '17 at 15:40