所以我有一個類處理按鈕,我有一個包含2個獨立矩形形狀的矩形數組。現在,當我做一個變量,檢索數組中的第0個索引時,它會給我一個nullpointerexception我一直在撓我的頭,我已經清楚地聲明並初始化數組,並使其包含2個矩形的適當大小,已將這些分配給索引。我必須錯過一些我似乎無法想象的小事。nullpointerexception當從矩形數組中檢索矩形
下面我已經把相關的代碼如下:
public class MenuButton {
private int height;
private int width;
private float positionX;
private float positionY;
//private ArrayList<Rectangle> rects;
private Rectangle rects[];
private Rectangle play;
private Rectangle touchToPlay;
private boolean isTouched;
public MenuButton(int height, int width, float positionX, float positionY){
this.height = height;
this.width = width;
this.positionX = positionX;
this.positionY = positionY;
isTouched = false;
Rectangle rects[] = new Rectangle[2];
play = new Rectangle(positionX, positionY, width, height);
touchToPlay = new Rectangle(positionX, positionY, width, height);
//can clean this up by introducing initButtons() to assign buttons to
//indexes of the array
rects[0] = play;
rects[1] = touchToPlay;
}
public boolean isClicked(int index,float screenX, float screenY){
//ERROR IS BELOW THIS LINE
Rectangle rect = rects[0];
return rect.contains(screenX, screenY);
}
哦,難怪爲什麼!啊哈。我一直在看和看,我沒有看到我犯的這個錯誤是如此明顯,但我沒有看到我意外地錯誤地初始化了它。 – 2014-10-27 20:42:14
+1提到術語陰影! – Chiseled 2014-10-27 20:47:10