出于某种原因,我收到了这个错误。
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++;
}
}
}
答案 0 :(得分:1)
自从counter1
开始1
以及for
次迭代6
循环后,counter1
在最后一次迭代中变为7,从而得到{ {1}}。由于ArrayIndexOutOfBoundsException
的大小为7,并且当array
变为7时,您尝试使用7
访问索引array[counter1]
。
数组中的最大可访问索引始终为counter1
,在您的情况下,array.length - 1
是数组的最后一个可访问索引。
答案 1 :(得分:1)
counter1
的初始值为1
,counter1
的值为7
i=6
。但是没有数组的索引。
答案 2 :(得分:0)
数组是针对大小7定义的,迭代只进行了6次...所以异常
答案 3 :(得分:0)
当您递增counter
和counter1
时,请将counter1
设为counter1
,使其完全为counter+1
。当counter
为array.length-1
时,您的counter1
等于array.length
7
。
由于您打算计算两个相邻整数的gcd,为什么不直接使用i
本身:
for(int i = 0; i < array.length -1 ; i++){ // <<---- array.length-1 = 6, i guess
long start1 = System.currentTimeMillis();
gcd2(array[i], array[i+1]);
// other code