【发布时间】:2020-08-14 04:42:12
【问题描述】:
我需要减去:
(2 - 0) 和 (4 - 2)。
我需要这个来找出丢失了多少数字。 我只是第一次学习编码,从逻辑上讲,这对我来说似乎是正确的。
只要“n”小于“4”的“(statues[statues.length-1])”,就应该在“2”处停止代码减法。 所以我不明白为什么会出现这个错误:
java.lang.ArrayIndexOutOfBoundsException:索引 3 超出长度 3 的范围
确实,如果我打印“c”,我可以看到正确的结果,但显然它一直在计算,因为错误行是“c”行。
我已将代码更改为不同的版本,它可以正常工作,但根据数组中的数字,出了点问题。
公共类 MakeArrayConsecutive2 {
public static void main(String[] args) {
int[] statues = {0, 2, 4};
makeArrayConsecutive2(statues);
}
public static int makeArrayConsecutive2(int[] statues) {
Arrays.sort(statues);
int count = 0;
for (int n = statues[0]; n < statues[statues.length-1]; n++) {
int c = statues[n + 1] - statues[n];
System.out.println(c);
if (c != 1) {
count += c - 1;
}
}
System.out.println(count);
return 0;
}
}
【问题讨论】:
-
您的循环将 n 初始化为 0,这是雕像数组的第一个元素,并且仅上升到 3,这是您的数组的最后一个元素,但您的数组的最后一个索引是 2,这就是为什么 n + 1 得到了 ArrayIndexOutOfBoundsException。
-
您的数组仅包含 3 个元素(有效索引从 0 到 2),您的循环从 0 到 3 运行,因此您超出了数组范围
标签: java arrays for-loop indexoutofboundsexception subtraction