0

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);
        }
    }
}
5
  • You’ve swapped rows and cols. You create and array [rows][cols] (swapping method argument order for some reason. You then loop y over rows and x over cols. Finally you assign [x][y] - i.e. [cols][rows]. Commented Oct 13, 2021 at 5:39
  • Please don’t edit your question to substantively change the question being asked once you have answers. Commented Oct 13, 2021 at 5:45
  • 1
    x < board[y].length + 1 - why +1 ? Commented Oct 13, 2021 at 5:46
  • @BoristheSpider Very sorry, I just noticed I had copied an older segment of code, the code currently up is what I have been having issues with, at this point should I delete the question and create a new post? Commented Oct 13, 2021 at 5:50
  • I would ask a new question, yes. This question has an upvoted answer which refers to the code you originally post. Please take a lesson away here - take at least as much effort asking your question as you expect people to take answering it; please proof read your questions! Commented Oct 13, 2021 at 5:56

1 Answer 1

2
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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.