简体   繁体   中英

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 . Because the size of your array is 7 and you're trying to access the index 7 using array[counter1] when counter1 becomes 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.

initial value of counter1 is 1 and value of counter1 will be 7 by i=6 . 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 . When counter is array.length-1 your counter1 is equal to array.length which is 7 .

As you intention is to compute gcd of two adjacent integer why not directly use i itself:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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