java - 为什么在第二个 For 循环中给出 ArrayIndexOutOfBoundsException?

标签 java arrays indexoutofboundsexception

为什么在第二个 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 在内部顺时针旋转数组。

最佳答案

您访问a[i+r],考虑循环的最后一次迭代。 i = a.length-r 因此 i+r = a.length-r + r = a.length 超出范围。

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

关于java - 为什么在第二个 For 循环中给出 ArrayIndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50895971/

相关文章:

java - 从同一列的组件菜单中删除 JTable 列时出错

java - jar 中的类什么时候进入 PermGen

java - JPA Hibernate 中的全局 setMaxResult

javascript - 插入存储在 JavaScript 对象值中的数组的奇怪行为

c++ - 从多个结构访问字段与访问数组/vector 的元素相比是否更慢?

java - 为什么 ArrayIndexOutOfBoundsException 不是编译时错误?

Java BufferedReader while循环越界异常

java - Android REST POST 丢失日期值

java - 调用fragment中的方法

php - 获取此 PHP 错误 : fputcsv() expects parameter 2 to be array