【问题标题】:Why is is giving me ArrayIndexOutOfBoundsException in second For loop?为什么在第二个 For 循环中给我 ArrayIndexOutOfBoundsException?
【发布时间】:2018-06-17 10:58:26
【问题描述】:

为什么在第二个 For 循环中给我ArrayIndexOutOfBoundsException

public class Ass1Ques2 {

    void rotate() {
        int[] a = {3, 8, 9, 7, 6};

        int r = 2;
        int[] t1 = new int[(a.length - r) + 1];
        int[] t2 = new int[r + 1];


        for (int y = 0; y <= r; y++) {
            t2[y] = a[y];
        }


        // This loop is giving error
        for (int i = 0; i <= a.length - r; i++) {
            t1[i] = a[i + r];
        }

        for (int f = 0; f <= t1.length; f++) {
            System.out.println(t1[f] + " ");
        }
        for (int n = 0; n <= t2.length; n++) {
            System.out.println(t2[n] + " ");
        }


    }

    public static void main(String[] args) {

        Ass1Ques2 r = new Ass1Ques2();
        r.rotate();

    }

}

我不知道如何解决这个错误,我想我给 t2 提供了正确的长度。
我想根据 r 在内部顺时针旋转数组。

【问题讨论】:

  • 只使用i &lt; a.length - r而不使用=
  • 最后两个循环中还有f &lt; t1.lengthn &lt; t2.length
  • 为什么要创建两个t1t2 数组?为什么每个循环都使用不同的迭代器名称(yifn)? for(int i=0; ...){..} 声明了自己的迭代器 i,其范围仅限于该特定循环。因此,您可以在每个非嵌套循环中重用该名称。

标签: java arrays indexoutofboundsexception


【解决方案1】:

您访问a[i+r],考虑循环的最后一次迭代。 i = a.length-r 所以i+r = a.length-r + r = a.length 越界了。

如果要旋转数组,我建议使用模 (%) 运算符来计算索引的新位置。所以在实践中,将旋转添加到所有索引并在数组长度上取模以获得新位置。

【讨论】:

    【解决方案2】:

    在循环的最后一次迭代中,您将访问 a.length,它返回从 1 开始的数组的整个长度;这会导致 IndexOutOfBounds 异常,因为索引从 0 开始。为了解决这个问题,只需执行以下操作:

    for (int i = 0; i < a.length - r; i++) {
        t1[i] = a[i + r];
    }
    

    这将防止 for 循环迭代到具有等号的数组的最后 非常 点,这会导致 IndexOutOfBounds 异常。

    【讨论】:

      猜你喜欢
      • 2019-12-23
      • 1970-01-01
      • 2021-10-16
      • 2017-12-07
      • 2017-04-27
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多