2014-10-27 88 views
2

所以我有一個類處理按鈕,我有一個包含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); 
} 

回答

7

特殊照顧shadowing變量rects。更換

Rectangle rects[] = new Rectangle[2]; 

rects = new Rectangle[2]; 
+0

哦,難怪爲什麼!啊哈。我一直在看和看,我沒有看到我犯的這個錯誤是如此明顯,但我沒有看到我意外地錯誤地初始化了它。 – 2014-10-27 20:42:14

+1

+1提到術語陰影! – Chiseled 2014-10-27 20:47:10

1

是的,rects變量是本地MenuButton構造函數(我認爲這是一個構造函數)。這意味着它隱藏了你在同一個名字中聲明的字段。所以你初始化了局部變量,然後在構造函數結束時,它不見了。該領域保持空虛。

+0

是的,這是你作爲一個程序員犯的錯誤之一,你犯了一些錯誤,你知道如何解決它,但有些情況下,即使在那裏你也不會看到它很長一段時間。 – 2014-10-27 20:43:56

1

您已聲明Rectangle rects[]兩次。只需將構造函數內部的行更改爲rects = new Rectangle[2];