繁体   English   中英

使数组索引超出界限错误

[英]Getting Array Index Out of Bounds Error

由于某种原因,我收到此错误。

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开始你的counter16次迭代的for循环,所以在最后一次迭代中counter1变为7,这给出了ArrayIndexOutOfBoundsException 因为你的尺寸array是7和你想访问索引7使用array[counter1]counter1变为7。

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

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

数组是为大小7定义的,迭代只进行了6次...所以例外

当你递增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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM