I am creating a text based minesweeper game in Java. The game works fine if a user creates a perfect square for a game board, however if they enter two different values, I get an exception at the point where I add the mines into the 2d array:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 19
at Grid.addMines(Grid.java:77)
Add mines (Line 77 is if statement):
public void addMines()
{
Random generator = new Random();
int count = 0;
while (count < numMines)
{
int x = generator.nextInt(rows);
int y = generator.nextInt(columns);
if (grid[x][y].minePresent == false)
{
grid[x][y].setCurrent("*");
grid[x][y].minePresent = true;
count++;
}
else
continue;
}
}
This looks suspicious to me:
int x = generator.nextInt(rows);
int y = generator.nextInt(columns);
Given that an x
value specifies a column usually, I suspect you want:
int x = generator.nextInt(columns);
int y = generator.nextInt(rows);
Or to be clearer still:
int column = generator.nextInt(columns);
int row = generator.nextInt(rows);
Then consistently either use:
Foo[][] grid = new Foo[rows][columns];
...
grid[row][column] = ...;
or:
Foo[][] grid = new Foo[columns][rows];
...
grid[column][row] = ...;
Either of those is fine, but you'd got the wrong order because you'd changed from a "column/row" model to an "x/y" model inconsistently.
It's worth taking a step back to work out how to diagnose similar problems in the future. If something works when two values are the same (rows and columns in this case) and fails when they're different, then usually that means you're using one of the values instead of the other somewhere. So trace your code carefully back from the error spot, working out anywhere where those values are used, and checking them.
See more on this question at Stackoverflow