Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从矩形数组中检索矩形时出现nullpointerexception_Java_Android_Arrays - Fatal编程技术网

Java 从矩形数组中检索矩形时出现nullpointerexception

Java 从矩形数组中检索矩形时出现nullpointerexception,java,android,arrays,Java,Android,Arrays,我有一个处理按钮的类,我有一个包含两个单独矩形的矩形数组。现在,当我创建一个变量来检索数组的第0个索引时,它会给我一个nullpointerexception,我一直在琢磨这个问题,我已经清楚地声明并初始化了数组,使它成为包含2个矩形的适当大小,并将它们分配给了索引。我一定错过了一些我似乎无法理解的小事情 以下是我的相关代码: public class MenuButton { private int height; private int width; private float posit

我有一个处理按钮的类,我有一个包含两个单独矩形的矩形数组。现在,当我创建一个变量来检索数组的第0个索引时,它会给我一个nullpointerexception,我一直在琢磨这个问题,我已经清楚地声明并初始化了数组,使它成为包含2个矩形的适当大小,并将它们分配给了索引。我一定错过了一些我似乎无法理解的小事情

以下是我的相关代码:

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);
} 
公共类菜单按钮{
私人内部高度;
私有整数宽度;
私有浮动位置X;
私人浮动头寸;
//私有数组列表矩形;
私有矩形矩形[];
私人矩形游戏;
私有矩形触摸屏;
私有布尔值被触发;
公共菜单按钮(整数高度、整数宽度、浮点位置X、浮点位置Y){
高度=高度;
这个。宽度=宽度;
此位置x=位置x;
这个位置y=位置y;
isTouched=false;
矩形矩形[]=新矩形[2];
播放=新矩形(位置X、位置Y、宽度、高度);
touchToPlay=新矩形(位置X、位置Y、宽度、高度);
//可以通过引入initButtons()将按钮分配给
//数组的索引
矩形[0]=播放;
rects[1]=touchToPlay;
}   
已单击公共布尔值(整型索引、浮点屏幕X、浮点屏幕Y){
//错误在这行下面
矩形rect=rects[0];
return rect.contains(screenX,screenY);
} 
您是变量
rects
。替换

Rectangle rects[] = new Rectangle[2];


是的,
rects
变量是
MenuButton
构造函数的本地变量(我假设它是一个构造函数)。这意味着它隐藏了您在类中以相同名称声明的字段。因此,您初始化了局部变量,然后在构造函数末尾,它消失了。字段仍然为空。

您声明了两次
矩形rects[]
。只需将构造函数内的行更改为
rects=new Rectangle[2]

哦,难怪!啊哈。我一直在看啊看,我没有看到我犯的错误。这是很明显的,但我只是没有看到我不小心把它初始化错了。是的,这是作为一个程序员犯的错误之一,你犯了一些错误,你知道如何修复它,但有些情况下你就是看不到它很长一段时间,即使它在那里。
rects = new Rectangle[2];