我正在嘗試爲動態壁紙創建一個正方形(自定義類)的二維數組。我計算了使用屏幕寬度和高度以及它們之間的方邊長度和間隙距離的最終整數來顯示的數量。初始化數組中的正方形時,我使用嵌套for循環。但是,當我在模擬器上運行這個時,我得到一個索引超出界限。ArrayIndexOutOfBounds與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);
}
}
}
}
學習使用調試器(你使用Eclipse?)將在稍後爲您節省大量的挫折。只是說。 – rolfl