I'm trying to run a method that calls my class method below. Everytime I call the method computeIterative(), I get an ArrayIndexOutOfBoundsException. I added some code to print out the loop, and I see that the exception occurs around the second time through the loop, but the loop continues until complete. What am I doing wrong that I can't solve this array exception?
static int computeIterative(int n) {
efficiency = 0;
int[] a = new int[n];
int firstInt = 0;
int secondInt = 1;
int results = 0;
if (n > 1) {
a[0] = 0;
a[1] = 1;
for (int i = 2; i <= n; ++i) {
efficiency++;
firstInt = a[i-1];
secondInt = a[i-2];
results = 2 * firstInt + secondInt;
System.out.println("Loop " + efficiency + " of " + n );
System.out.println(firstInt);
System.out.println(secondInt);
System.out.println("Results: " + results);
a[i] = results;
}
} else {
a[0] = 0;
a[1] = 1;
}
return a[n];
}
Thank you for the help.