ArrayIndexOutOfBoundsException 当我询问的数组索引没有超出范围时

ArrayIndexOutOfBoundsException when the array index I ask doesn't go out of bounds

我一直遇到的问题是它说 java.lang.ArrayIndexOutOfBoundsException: 165

165 是它实际应该包含的值的数量。

我尝试将整数数组的长度更改为更大的数字,但它保持不变 给我错误,是更大的数字。

我打印了所有内容,看看问题是否出在我的 for 循环上, 但那里的一切似乎都很好(165 个数组中有正确的数字)

我看不出问题出在哪里。

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.

对 - 那么索引 165 越界了。

Java 中的数组是从 0 开始的,因此如果一个数组有 165 个值,则有效索引为 0 到 164(含)。

您的 for 循环应该使用 < 而不是 <= 作为边界:

for (int y = 0; y < heightInTiles; y++) {
    for (int x = 0; x < widthInTiles; x++) {