for循环中数组元素的减法(java.lang.ArrayIndexOutOfBoundsException)

Subtraction of array elements in for loop (java.lang.ArrayIndexOutOfBoundsException)

我需要减去:

(2 - 0) 和 (4 - 2)。

我需要这个来查找丢失了多少个数字。 我只是第一次学习编码,逻辑上对我来说似乎是正确的。

代码减法只要 "n" 小于 "(statues[statues.length-1])" 即 "4",所以它应该在 "2" 处停止。 所以我不明白为什么会出现此错误:

java.lang.ArrayIndexOutOfBoundsException: 索引 3 超出长度 3

的确,如果我打印 "c" 我可以看到正确的结果,但显然它一直在计算,因为错误行是 "c" 行。

我已经将代码更改为不同的版本并且它可以工作,但是根据数组中的数字,出现了问题。

public class 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;

}

}

这里的主要误解似乎是关于如何 在 for 循环中迭代某些结构。在这里,你写了

for (int n = statues[0]; n < statues[statues.length-1]; n++) {
    int c = statues[n + 1] - statues[n];
}

这是不正确的,因为当您尝试使用雕像[statues[2]] 时,您实际上是在使用不存在的雕像[4];你可能只想引用雕像[n]。对此的解决方案是将 n 视为一个常规整数,它采用 [0, statues.length - 1) 范围内的所有值。这看起来更像

for (int n = 0; n < statues.length - 1; n++) {
    int c = statues[n + 1] - statues[n];
}

希望对您有所帮助,如果我对您的意图的理解有误,请告诉我。