【发布时间】: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 < a.length - r而不使用= -
最后两个循环中还有
f < t1.length和n < t2.length -
为什么要创建两个
t1和t2数组?为什么每个循环都使用不同的迭代器名称(y、i、fn)?for(int i=0; ...){..}声明了自己的迭代器i,其范围仅限于该特定循环。因此,您可以在每个非嵌套循环中重用该名称。
标签: java arrays indexoutofboundsexception