Java 为什么在第二个For循环中给我ArrayIndexOutOfBoundsException?
为什么给我Java 为什么在第二个For循环中给我ArrayIndexOutOfBoundsException?,java,arrays,indexoutofboundsexception,Java,Arrays,Indexoutofboundsexception,为什么给我ArrayIndexOutOfBoundsException在秒For循环中 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 =
ArrayIndexOutOfBoundsException
在秒For循环中
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();
}
}
公共类关联2{
void rotate(){
int[]a={3,8,9,7,6};
int r=2;
int[]t1=新的int[(a.length-r)+1];
int[]t2=新的int[r+1];
对于(int y=0;y您访问<代码> a[i+r] < /代码>,考虑循环的最后一次迭代。<代码> i=A.thth-r >“代码> I+R=A.Trthth-R+R= A.长度超出界限。
如果要旋转数组,建议使用模(%)运算符来计算索引的新位置。因此,在实践中,将旋转添加到所有索引,并在数组长度上进行模运算,以获得新位置。在循环的最后一次迭代中,您将访问a.length,它返回从1开始的数组的整个长度;这将导致从中开始的IndexOutOfBounds异常骰子从0开始。要解决此问题,只需执行以下操作:
for (int i = 0; i < a.length - r; i++) {
t1[i] = a[i + r];
}
for(int i=0;i
这将防止for循环以等号迭代到数组的最后一个点,这将导致indexootfbounds异常。只需使用i
而不使用=
也f
和n
在最后两个循环中您为什么要创建两个t1
和t2
首先是数组?为什么每个循环使用不同的迭代器名称(y
,i
,f
n
)?for(int i=0;…){..
声明自己的迭代器i
,其范围仅限于该特定循环。因此,可以在每个非嵌套循环中重用该名称。