gpt4 book ai didi

java - TileMap ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-11-30 03:44:59 24 4
gpt4 key购买 nike

我正在尝试制作一个 TileMap,但是当我去渲染tileMap 并迭代 map 中的所有整数时,我得到一个ArrayIndexOutOfBoundsException

这是渲染方法:

public void render(Renderer renderer) {

for (int x = 0; x < map[1].length; x++) {
for (int y = 0; y < map[0].length; y++) {

if (map[y][x] == -1) {
continue;
}

renderer.getGraphics().drawImage(tileSet.get(map[y][x]).getTexture(), (x * tileSize) + xOffs, (y * tileSize) + yOffs, null);
}
}
}

这是 map :

map = new int[][] {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
};

这是错误:

Exception in thread "Thread-2" java.lang.ArrayIndexOutOfBoundsException: 3
at game.TileMap.render(TileMap.java:37)
at game.Main.render(Main.java:57)
at engine.GameLoop.render(GameLoop.java:87)
at engine.GameLoop.run(GameLoop.java:66)
at java.lang.Thread.run(Unknown Source)

最佳答案

您错误地迭代了数组。 map[0].lengthmap[1].length 解析为 15,因为:

map[0] == {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
map[1] == {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}

因此,当 y 为 3(或更大)时,您会在 map[y][x] 处得到异常。这是因为您尝试访问 map[3] 处的数组,但它仅包含 3 个元素(正如您所知,数组是从零开始的)。

通过调试,我确信您可以找出出现异常的原因,并正确初始化循环。提示是,map 实际上是一个数组的数组,这意味着 map[i] 返回索引 i 处的数组,如上所述。

关于java - TileMap ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25976351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com