2014-10-27 46 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];