Reputation: 340
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++;
}
}
}
Upvotes: 0
Views: 94
Reputation: 15408
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
Upvotes: 0
Reputation: 446
Array is defined for size 7 and the iterations are carried only 6 times...so the exception
Upvotes: 0
Reputation: 35547
initial value of counter1
is 1
and value of counter1
will be 7
by i=6
. But there isn't a index for array.
Upvotes: 1
Reputation: 45060
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.
Upvotes: 1