简体   繁体   English

使数组索引超出界限错误

[英]Getting Array Index Out of Bounds Error

For some reason I am getting this 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++;
    }
}

} }

Since you start your counter1 from 1 and the for loops for 6 iterations, the counter1 becomes 7 in the last iteration which gives the ArrayIndexOutOfBoundsException . 由于你从1开始你的counter16次迭代的for循环,所以在最后一次迭代中counter1变为7,这给出了ArrayIndexOutOfBoundsException Because the size of your array is 7 and you're trying to access the index 7 using array[counter1] when counter1 becomes 7. 因为你的尺寸array是7和你想访问索引7使用array[counter1]counter1变为7。

The maximum accessible index in array is always array.length - 1 , in your case, array[6] is the last accessible index of your array. 数组中的最大可访问索引始终是array.length - 1 ,在您的情况下, array[6]array[6]的最后一个可访问索引。

initial value of counter1 is 1 and value of counter1 will be 7 by i=6 . counter1初始值为1并且i=6counter1值为7 But there isn't a index for array. 但是没有数组的索引。

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

When you are incrementing counter and counter1 , you set counter1 as counter1 to be exactly counter+1 . 当你递增countercounter1 ,你将counter1设置为counter1 ,使其完全为counter+1 When counter is array.length-1 your counter1 is equal to array.length which is 7 . counterarray.length-1你的counter1等于array.length ,即7

As you intention is to compute gcd of two adjacent integer why not directly use i itself: 因为你打算计算两个相邻整数的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