The problem I keep having is that it says java.lang.ArrayIndexOutOfBoundsException: 165
165 is the number of values it should actually contain.
I tried changing the length of the integer array to a bigger number but it kept giving me the error, be it with a bigger number.
I printed everything out to see if maybe the problem was my for loop, but everything there seems fine (does 165 arrays with the right numbers in them)
I can't see where the problem is.
public int[][] getTilePositionsIn(int pixelLeft, int pixelBottom, int pixelRight, int pixelTop){
int starterTileX = pixelLeft/getTileLength();
if (starterTileX < 0)
starterTileX = 0;
System.out.println(starterTileX);
int starterTileY = pixelBottom/getTileLength();
if (starterTileY < 0)
starterTileY = 0;
System.out.println(starterTileY);
int tileLength = getTileLength();
int blockWidth = pixelRight - pixelLeft + 1;
int widthInTiles = blockWidth/tileLength +1;
int blockHeight = pixelTop - pixelBottom + 1;
int heightInTiles = blockHeight/tileLength +1;
int numberOfTiles = widthInTiles * heightInTiles;
System.out.println(widthInTiles);
System.out.println(heightInTiles);
System.out.println(numberOfTiles);
int[][] tiles = new int[numberOfTiles][2];
for (int y = 0; y <= heightInTiles; y++) {
for (int x = 0; x <= widthInTiles; x++) {
int index = y*widthInTiles + x;
System.out.println(index);
tiles[index][0] = x;
tiles[index][1] = y;
System.out.println(Arrays.toString(tiles[index]));
}
}
return tiles;
}
The problem I keep having is that it says java.lang.ArrayIndexOutOfBoundsException: 165
165 is the number of values it should actually contain.
Right - then index 165 is out of bounds.
Arrays in Java are 0-based, so if an array has 165 values, the valid indexes are 0 to 164 inclusive.
Your for
loops should use <
instead of <=
for the bounds:
for (int y = 0; y < heightInTiles; y++) {
for (int x = 0; x < widthInTiles; x++) {
See more on this question at Stackoverflow