I was making boards for the tic-tac-toe/connect four/mastermind when I encountered this strange error.
public Board(int rows, int columns) {
cells = new Cell[rows][columns];
for(int r = 0; r < cells[0].length; r++) {
for(int c = 0; c < cells[1].length; c++) {
cells[r][c] = new Cell(r, c);
}
}
When I tried to make a 3 x 3 board for tic-tac-toe, there was no problem whatsoever. However, when I tried to make 6 x 7 board for Connect 4, the following error message was displayed:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
at games.board.Board.<init>(Board.java:10)
at games.board.BoardGameTester.main(BoardGameTester.java:7)
By debugging the program, I realized that when the number of columns is bigger than the number of rows, an error occurs. I also realized that the error occurs because the outer for loop increments once more than the length of the row. But for loop incrementing without executing first? Wow.
I'm pretty sure that the increment statement is executed after the execution of the body.