2016-12-20 21 views
-4

我正在使用LibGDX爲android構建遊戲。 我在這個類中得到一個空指針異常,但我不知道爲什麼(檢查註釋)。Java - 方法調用中的空指針異常

public class ScoreFont { 
    private Texture _numbers[]; 
    private int _number; 

    public ScoreFont(){ 
     //Load font 
     for(int i = 0; i <= 9; i++){ 
      _numbers = new Texture[10]; 
      _numbers[i] = new Texture("font_"+i+".png"); 
      /*the line above works fine. if I use if(_number[i] != null) System.out.println("loaded"); it will print*/ 

     } 
     _number = 0; 
    } 

    public void setNumber(int number){ 
     _number = number; 
    } 

    public void draw(SpriteBatch sb, float x, float y, float width, float height){ 
     String numberString = Integer.toString(_number); 

     int numDigits = numberString.length(); 
     float totalWidth = width * numDigits; 

     //Draw digits 
     for(int i = 0; i < numDigits; i++){ 
      int digit = Character.getNumericValue(numberString.charAt(i)); 

      /*I get a null pointer exception when this method or the dispose() method are called. The _numbers[digit] == null, or even if I switch it for _numbers[0] it is still null. Why?*/ 
      sb.draw(_numbers[digit], x - totalWidth/2 + i*width, y - height/2, width, height); 
     } 
    } 

    public void dispose(){ 
     //I get null pointer exception 
     for(Texture texture: _numbers){ 
      texture.dispose(); 
     } 
    } 
} 

這裏可能發生了什麼?該函數的構造函數必須在任何方法之前始終調用,這將保證紋理總是正確加載?那麼,爲什麼我會得到一個空指針異常?

謝謝!

+0

@ John3136我知道什麼是NullPointerException,我只是無法在這裏找到錯誤。我真的認爲你應該在採取行動之前閱讀整個問題。 –

+2

您的構造函數。每循環一次,您都會創建一個新的紋理[10]。當循環退出時,只有'_numbers [9]'不會爲空 –

+2

應該不要緊,你知道它是什麼 - 調試,設置斷點。打印值。找出*爲什麼*。 –

回答

1
_numbers = new Texture[10]; 
_numbers[i] = new Texture("font_"+i+".png"); 

在您創建一個新的陣列中的每個迭代循環,這意味着,當循環結束,你將有一個新的數組與剛剛過去的元素初始化。 將數組的創建移出循環。