重新创建阵列后的NPE

时间:2014-08-17 11:55:32

标签: java opengl

我正在尝试创建一个X×Y方格,当到达边时会自动扩展,但是,每当它尝试渲染其中一个新方块时,我都会得到一个空指针异常,它会抛出一个null指针异常,尽管上一行检查变量是否使用了null。

这可能是愚蠢的事情,因为我现在要回到几个月前开始的写作,并且从那以后就已经忘记了很多。 这是我的代码:

    public static void renderMapSquare(MapSquare sq)
{
    System.out.println("[MS] " + sq.y + " is sq null? " + (sq.color == null));

    Render.setColor(sq.color); //Null Pointer Here
    Render.Triangle(sq.a);

    Render.setColor(sq.color);
    Render.Triangle(sq.b);

    Render.setColor(sq.color);
    Render.Triangle(sq.c);

    Render.setColor(sq.color);
    Render.Triangle(sq.d);      

    Render.BorderMapSquare(sq);
}

ExtendMap方法

    private void extendMapY(int extension)
{
    MapSquare[][] mapSquaresTemp = new MapSquare[mapSquares.length][mapSquares[0].length + extension];
    RTSLogging.log(this.getClass(), "Recreated mapsquares with x " + mapSquaresTemp.length + " y " + mapSquaresTemp[0].length);

    for (int i = 0; i < mapSquares.length; i++)
    {
        for (int j = 0; j < mapSquares[0].length; j++)
            mapSquaresTemp[i][j] = mapSquares[i][j];
    }
    System.out.println(mapSquares.length + " " + mapSquaresTemp.length);
    System.out.println(mapSquares[0].length + " " + mapSquaresTemp[0].length);

    for (int i = mapSquares.length -1; i < mapSquaresTemp.length; i++)
    {
        for (int j = mapSquares[0].length -1; j < mapSquaresTemp[0].length; j++)
        {
            MapSquare temp = new MapSquare(i, j);
            mapSquaresTemp[i][j] = temp;

        }
    }

    BoundPY += extension;
    mapSquares = mapSquaresTemp;
}

绘制方法

    public void draw(int eyeX, int eyeY)
{
    for (int x = eyeX - 50; x <= eyeX + 50; x++)
    {
        for (int y = eyeY - 50; y <= eyeY + 50; y++)
        {
            if ((x < BoundNX || y < BoundNY))
            {
                continue;
            }
            else
            {
                if (x > BoundPX || y > BoundPY)
                {
                    RTSLogging.log(this.getClass(), "We hit a wall");                       
                    if (x > BoundPX)
                    {
                        this.extendMapX(100);
                        break;
                    }
                    if (y > BoundPY)
                    {
                        this.extendMapY(100);
                        break;
                    }

                }
                Render.renderMapSquare(mapSquares[x][y]);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的extendMapY错误。

您将x * y元素数组扩展为x * (y + extension),但不初始化所有新元素。

应该是:

for (int i = 0; i < mapSquaresTemp.length; i++)
{
    for (int j = mapSquares[0].length; j < mapSquaresTemp[0].length; j++)
    {
        MapSquare temp = new MapSquare(i, j);
        mapSquaresTemp[i][j] = temp;

    }
}