gpt4 book ai didi

java - 类构造函数中的 ArrayIndexOutOfBounds

转载 作者:行者123 更新时间:2023-12-01 12:06:01 28 4
gpt4 key购买 nike

public class Environment {
//variables
RoundingStage[][] land;
int horizontalStreets;
int verticalStreets;

public Environment(RoundingStage[][] grid) {
this.horizontalStreets = grid.length;
this.verticalStreets = grid[0].length;
land = new RoundingStage[horizontalStreets][verticalStreets];

for (int i = 0 ; i <= horizontalStreets ; i++)
for (int j = 0 ; j <= verticalStreets ; j++)
land[i][j] = grid[i][j];
}
public Environment(Environment env) {
this.horizontalStreets = env.horizontalStreets;
this.verticalStreets = env.verticalStreets;
land = new RoundingStage[horizontalStreets][verticalStreets];

for (int i = 0 ; i <= horizontalStreets ; i++)
for (int j=0 ; j <= verticalStreets ; j++)
land[i][j] = env.land[i][j];
}

有人可以告诉我为什么当我使用这个函数时我会得到ArrayOutOfBound,我已经尝试了+1、-1的每种组合,我需要一些帮助:D

public RoundingStage valueInPosition(int rHor, int rVer) {
return land[rHor-1][rVer-1];
}

最佳答案

您实际上应该在这些构造函数中获得超出范围的异常。这些嵌套循环使用 ij因为迭代器应该循环直到 i < horizontalStreetsj <verticalStreets ,不是<=正如目前发布的那样。 Java 数组索引从 0 开始。

关于java - 类构造函数中的 ArrayIndexOutOfBounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27593721/

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