tbatch
tbatch

Reputation: 1849

Need help solving ArrayIndexOutOfBounds Exception in Java

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.

Upvotes: 0

Views: 48

Answers (3)

Shashaank V V
Shashaank V V

Reputation: 740

the error lies in the line

a[i] = results;

since in your for loop, you have been using :

for(i=2;i<=n;i++)

You will find that the array index starts from 0 and goes up to n-1. So when you are using :

i <= n

you will encounter an array out of bounds exception because it does not have a 'n'th element.

Change your for loop condition from :

i <= n 

to :

i < n

and your code should work.

Upvotes: 3

srinij
srinij

Reputation: 195

You have initiated array with size "n", you are trying to access a[n] element, array index starts from 0 to n-1.So when you access a[n] you are getting Arrayindexboundexception. change this line from

int[] a = new int[n]; to int[] a = new int[n+1]; (line 3)

Works!!

Upvotes: 0

Spide
Spide

Reputation: 89

If n is 2, you access a[2] (a[i] = results;) but there are only element 0 and 1

Upvotes: 0

Related Questions