我有這樣的代碼:這爲什麼會導致空指針異常?
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());
這是爲什麼?
將代碼發送到您調用'Sprite'構造函數的地方。 –
您確定您正在調用正確的Sprint構造函數,而不是沒有參數的默認構造函數嗎?你確定傳入的圖像在構造函數中不是null嗎?我會添加一些像'if(image!= null){this.image = image} else {image = new Image()};'你也想要確保圖像中的x和y不是null以及。 – bittersweetryan
如果遇到NullPointerException,請始終提供堆棧跟蹤...使用調試器來確定哪個變量確實爲空。 – home