0

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.

3 Answers 3

3

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.

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

Comments

0

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!!

1 Comment

This was exactly what I needed. I changed to int[n+1] and the program works perfect now. Thank you.
0

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

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.