Hi i’m writing a program thats using 2 dimensional int arrays in java. whenever i try to create the array with two different numbers it throws an ArrayIndex out of bounds.
An Example of this would be…
private int[][] tileMap;
public EditWindow(int rows, int columns, int tileSize){
this.columns = columns;
this.rows = rows;
this.tileSize = tileSize;
addMouseListener(this);
tileMap = new int[rows][columns];
}
If i set rows and columns to be the 10, for example, the code runs flawlessly but as soon as i set it to two different values(10 and 20 for example) it throws An error.
If theres something i didn’t explain well or you need more code to understand the question let me know
The code you’ve posted here is fine. ArrayIndexOutOfBoundsException is normally thrown when you’re accessing your array, not creating it. I’d guess that you’ve got a nested for loop somewhere in your code. Something like:
That’s the code you need to look at. Make sure that you have your ‘currRow’ and ‘currCol’ around the right way, and that you’re using the right ones in each place.
If you get your array indices around the wrong way (tileMap[currCol][currRow] instead of tileMap[currRow][currCol]) then you will get just such an exception in every case except where rows == columns (because if they’re the same, you’ll never try to find a column or row which doesn’t exit)