由于某种原因,我收到此错误。
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Assignment25.main(Assignment25.java:80)
public static void main (String[] args){
long[] array = new long[7];
for (int i = 0; i < 6; i++){
int thefib = 39;
array[i] = fib(thefib);
thefib++;
}
int counter = 0;
int counter1 = 1;
for(int i = 0; i < 6; i++){
long start = System.currentTimeMillis();
gcd(array[counter], array[counter1]);
long end = System.currentTimeMillis();
long time = end - start;
System.out.println("GCD time for " + (counter + 39) + " and " + (counter1 +
39) + " is " + time);
counter++;
counter1++;
}
counter = 0;
counter = 1;
for(int i = 0; i < 6; i++){
long start1 = System.currentTimeMillis();
gcd2(array[counter], array[counter1]);
long end1 = System.currentTimeMillis();
long time1 = end1 - start1;
System.out.println("GCD2 time for " + (counter + 39) + " and " + (counter1 +
39) + " is " + time1);
counter++;
counter1++;
}
}
}
最佳答案
由于您从 1
启动 counter1
以及 for
循环进行 6
迭代, counter1
在最后一次迭代中变为 7,从而产生 ArrayIndexOutOfBoundsException。因为 array
的大小为 7,并且当 counter1< 时,您尝试使用
array[counter1]
访问索引 7
/code> 变为 7。
数组中的最大可访问索引始终为array.length - 1
,在您的情况下,array[6]
是数组的最后一个可访问索引。
关于java - 数组索引越界错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198076/