2017-02-20 136 views
-2

我有這樣的代碼非常簡單:Java代碼說:NullPointerException異常

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); 
    } 

} 

而且這樣的:

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(); 
    } 
} 

,你可以看到我想要的球員類的實例添加到鏈接列表。但它返回一個錯誤:

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) 

我做錯了什麼?

+0

你的''Render''類實例化一個''Player''對象,該對象訪問''Main.controllable''爲null。 – f1sh

+0

它不是重複的,因爲我知道什麼是NullPointerExc,我知道如何解決它。 – Ervin

+2

那爲什麼不修好? – f1sh

回答

2

controllable未實例化。將它替換爲Main:

public static LinkedList<Player> controllable = new LinkedList<>(); 
+1

我也將它移動幾行,要創建之前渲染構造函數被稱爲 – user902383

+0

_not instantiated_還;)這是一個很好地與靜態和非靜態上下文混合。 – AxelH

+0

給那裏的所有人,以及這樣的準備活動是否值得回味:這就是我正在等待的答案! Thak You tak3shi – Ervin