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

问题描述 投票:0回答:1

我需要减去:

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

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

只要“ n”小于“(statues [statues.length-1])”(即“ 4”,则减去代码,因此应在“ 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;

}

}

java arrays for-loop indexoutofboundsexception subtraction
1个回答
0
投票

似乎这里的主要误解是关于how迭代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];
}

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

© www.soinside.com 2019 - 2024. All rights reserved.