带有For循环的ArrayIndexOutOfBounds

-1 java android for-loop live-wallpaper indexoutofboundsexception

我正在尝试为动态壁纸创建一个2D正方形阵列(自定义类).我计算了使用屏幕宽度和高度以及方形边长和它们之间的间隙距离的最终整数可以显示的数量.初始化数组中的方块时,我使用嵌套for循环.但是,当我在模拟器上运行它时,我得到一个超出范围的索引.

java.lang.ArrayIndexOutOfBoundsException:length = 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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Daw*_*ica 5

在里面initSquares,你有for(int j=0; j<numSquaresH; i++).for应该是最后一个条款j++.