2011-09-07 85 views
0

我有這樣的代碼:這爲什麼會導致空指針異常?

public class Sprite { 
    protected float x; 
    protected float y; 
    protected Image image; 
    protected Rectangle boundingBox; 

    Sprite(float x, float y, Image image) { 
     this.x = x; 
     this.y = y; 
     this.image = image; 
     boundingBox = new Rectangle(x, y, 
      this.image.getWidth(), this.image.getHeight()); 
    } 

...

public Rectangle getBoundingBox() { 
    return boundingBox; 
} 

但是當我調用不同類此功能,一旦組圖對象已經定義並初始化:

public static boolean collides(Sprite object1, Sprite object2) { 
    return object1.getBoundingBox().intersects(object2.getBoundingBox()); 
} 

我收到一個空指針異常,指向包含此行的行:

this.image.getWidth(), this.image.getHeight()); 

這是爲什麼?

+0

將代碼發送到您調用'Sprite'構造函數的地方。 –

+0

您確定您正在調用正確的Sprint構造函數,而不是沒有參數的默認構造函數嗎?你確定傳入的圖像在構造函數中不是null嗎?我會添加一些像'if(image!= null){this.image = image} else {image = new Image()};'你也想要確保圖像中的x和y不是null以及。 – bittersweetryan

+0

如果遇到NullPointerException,請始終提供堆棧跟蹤...使用調試器來確定哪個變量確實爲空。 – home

回答

1

某處你正在創建一個Sprite並傳遞構造函數爲空圖像。在你的構造嘗試做這樣的

if (image == null) throw new Exception("Cannot create Sprite with null image")

5

檢查圖像是否爲空。這很可能是錯誤來自何處。

+0

但圖像不爲空,因爲它已被定義。 – Derek

+0

@Deza - 也許你在構造函數中用'null'初始化它。 –

+0

參數圖像?你顯示this.image.getWidth()/ getHeight()是NPE來自哪裏,唯一的邏輯解決方案是A)它是空的,而且這種情況永遠不會發生,或者B)該圖像爲空。如果圖像爲null,則this.image可以爲null。 – Nicholas

0

東西,如果imagenull它會發生。某處在你的代碼,你必須作出這一呼籲:

new Sprite(aFloat, anotherFloat, aNullValue); // aNullValue == null 

你可能想添加一些null在構造函數拋出一個RuntimeException檢查。這將使您很容易找到在nullImage中傳遞的代碼。