title: ArrayIndexOutOfBounds with For loops
body: <p>I am trying to create a 2D array of squares (custom class) for a live wallpaper.  I calculate how many can be displayed using the screen width and height and final ints for the square side length and gap distance between them.  When initializing the squares in the array I use nested for loops.  However, when I run this on an emulator I get an index out of bounds.</p>
  
  <blockquote>
    <p>java.lang.ArrayIndexOutOfBoundsException: length=6; index=6</p>
  </blockquote>
  
  <p>Why would the for loop not work?</p>
  
  <pre><code>@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) &lt; (numSquaresW + 1) * SQUARE_GAP)
              numSquaresW--;
      while(height % (numSquaresH * SQUARE_SIDE) &lt; (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&lt;numSquaresW; i++)
          {
              for(int j=0; j&lt;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);
              }
          }
      }
  }
  </code></pre>