我正在尝试创建一个 X × Y 的正方形网格,该网格在到达边缘时会自动扩展,但是,每当它尝试渲染新正方形之一时,我都会收到空指针异常,它会抛出空值指针异常,尽管前一行检查变量是否使用 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]);
}
}
}
}
最佳答案
你的extendMapY是错误的。
您将 x * y
元素数组扩展为 x *(y + 扩展名)
,但并未初始化所有新元素。
应该是:
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;
}
}
关于java - 重新创建数组后的 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25348960/