我正在尝试为动态壁纸创建一个二维正方形数组(自定义类)。我使用屏幕宽度和高度以及正方形边长和它们之间的间隙距离的最终整数来计算可以显示的数量。在初始化数组中的正方形时,我使用嵌套的 for 循环。但是,当我在模拟器上运行它时,我得到一个超出范围的索引。
java.lang.ArrayIndexOutOfBoundsException:长度=6;索引=6
为什么 for 循环不起作用?
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
this.width = width;
this.height = height;
calcSquares();
initSquares();
super.onSurfaceChanged(holder, format, width, height);
}
private void calcSquares()
{
numSquaresW = width/SQUARE_SIDE;
numSquaresH = height/SQUARE_SIDE;
while(width % (numSquaresW * SQUARE_SIDE) < (numSquaresW + 1) * SQUARE_GAP)
numSquaresW--;
while(height % (numSquaresH * SQUARE_SIDE) < (numSquaresH + 1) * SQUARE_GAP)
numSquaresH--;
marginW = ((width % numSquaresW) - ((numSquaresW - 1) * SQUARE_GAP)) / 2;
marginH = ((height % numSquaresH) - ((numSquaresH - 1) * SQUARE_GAP)) / 2;
squares = new WallpaperSquare[numSquaresW][numSquaresH];
}
private void initSquares()
{
synchronized(squares)
{
for(int i=0; i<numSquaresW; i++)
{
for(int j=0; j<numSquaresH; i++)
{
int color = Color.HSVToColor(new float[] { (float) (360.0 * Math.random()), 1.0f, 1.0f });
int xLoc = marginW + (SQUARE_SIDE + SQUARE_GAP) * i;
int yLoc = marginH + (SQUARE_SIDE + SQUARE_GAP) * j;
squares[i][j] = new WallpaperSquare(xLoc, yLoc, color);
}
}
}
}