Java:object []中的NullExceptionPointer

时间:2014-04-04 13:54:35

标签: java arrays object nullpointerexception null

我正在尝试检查单元格的状态是否为真值。如果状态为真,那么我将保存元素的X和Y(2D数组)。这是我正在使用的方法,其中c是计算真实细胞数的计数器:

public void checkState(){
        System.out.println("Checking State");
        int c = 0;

        for(int y = 0; y < GRID_Y; y++){
            for(int x = 0;x < GRID_X; x++){
                if(state[x][y]==true){
                    //Error starts after this line
                    coords[c].setX(x);
                    coords[c].setY(y);
                    c++;

                    //DEBUG

                        System.out.println(coords.getX());
                        System.out.println(coords.getY());
                }

            }
        }
        System.out.println(c);
    }
}

coords对象声明如下:

  

私人Coords [] coords =新Coords [totalCells];

(尝试将totalCells更改为像10这样的小整数值,仍然无效)

Coords类是:

public class Coords {
    int x,y;

    public Coords(){
        x = 0;
        y = 0;
    }

    public void setX(int xIn){
        x = xIn;
    }

    public void setY(int yIn){
        y = yIn;
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }

}

我收到以下错误:

Checking State
java.lang.NullPointerException
    at game.GameOfLifeGUI.checkState(GameOfLifeGUI.java:116)
    at game.GameOfLifeGUI.<init>(GameOfLifeGUI.java:57)
    at game.GameOfLifeGUI$1.run(GameOfLifeGUI.java:32)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

我没有得到如何传递空值,因为我正在存储for循环的x和y。

感谢您的时间。

2 个答案:

答案 0 :(得分:3)

之后:私人Coords [] coords =新Coords [totalCells];

添加:

for(int index = 0; index < totalCells-1; index++){
    coords[index] = new Coords();
}

应该做的伎俩

答案 1 :(得分:1)

虽然@ user3497004的答案适用于java&lt; 8,你应该更喜欢:

Arrays.setAll(coords, n -> new Coords());

对于java 8(可能在上面,让我们充满未来感)。