0

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

}

1
  • 2
    The reason is that you are using an index that's outside the array. Commented Nov 25, 2013 at 16:30

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

initial value of counter1is 1 and value of counter1 will be 7 by i=6. But there isn't a index for array.

Comments

0

Array is defined for size 7 and the iterations are carried only 6 times...so the exception

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.