使数组索引超出界限错误

时间:2013-11-25 16:28:21

标签: java arrays

出于某种原因,我收到了这个错误。

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++;
    }
}

}

4 个答案:

答案 0 :(得分:1)

自从counter1开始1以及for次迭代6循环后,counter1在最后一次迭代中变为7,从而得到{ {1}}。由于ArrayIndexOutOfBoundsException的大小为7,并且当array变为7时,您尝试使用7访问索引array[counter1]

数组中的最大可访问索引始终为counter1,在您的情况下,array.length - 1是数组的最后一个可访问索引。

答案 1 :(得分:1)

counter1的初始值为1counter1的值为7 i=6。但是没有数组的索引。

答案 2 :(得分:0)

数组是针对大小7定义的,迭代只进行了6次...所以异常

答案 3 :(得分:0)

当您递增countercounter1时,请将counter1设为counter1,使其完全为counter+1。当counterarray.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