willguyturner
willguyturner

Reputation: 1

How to create rectangular 2d array in Java?

I'm trying to create a minesweeper clone for school and looking to create a variable board size, the below code works to create a 2d minefield but I get an arrayIndex out of bounds error when columns != rows. Any help would be appreciated. Amateur code so any other advice is welcome.

public void genBoard(int columns, int rows) {
    board = new Tile[rows][columns];
    for (int y = 0; y < rows; y++) {
        for (int x = 0; x < board[y].length + 1; x++) {
            board[x][y] = new Tile(x, y, 0, false);
        }
    }
}

Upvotes: 0

Views: 74

Answers (1)

Stephan Branczyk
Stephan Branczyk

Reputation: 9385

x < board[y].length + 1;

should be

x < board[y].length;

That is what is causing the index out of bound error.

But also, board[x][y] should be board[y][x]

Upvotes: 2

Related Questions