gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:06:49 27 4
gpt4 key购买 nike

为什么在第二个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com