【问题标题】:Subtraction of array elements in for loop (java.lang.ArrayIndexOutOfBoundsException)for循环中数组元素的减法(java.lang.ArrayIndexOutOfBoundsException)
【发布时间】: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


【解决方案1】:

这里的主要误解似乎是关于 如何 在 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];
}

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

【讨论】:

  • 非常感谢您的帮助。您不仅给了我解决方案,而且我得到了关于迭代的解释,现在很清楚了。它完美地适用于所有测试。
猜你喜欢
  • 2023-03-13
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多