Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 1000000 at problem2.main(problem2.java:17)



I get the following error and I don’t know why. I tried looking it up, but I didn’t find a solution.

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 1000000 at problem2.main(problem2.java:17)

Here is my code:

//Each new term in the Fibonacci sequence is generated by adding the previous two terms.
//By starting with 1 and 2, the first 10 terms will be:
//1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
//By considering the terms in the Fibonacci sequence whose values do not exceed four million, 
//find the sum of the even-valued terms.

public class problem2 {
    public static void main(String[] args) {
        int []a = new int[1000000];
        a[0] = 1;
        a[1] = 2;
        int sum=0;

        int i=2;
        while(a[i]<=4000000){
            a[i] = a[i-1] + a[i-2];
            i++;
        }

        for(int j=0;j<i;j++){
            sum = sum + a[j];
        }

        System.out.println("The sum is: " + sum);
        System.out.println("nThere are " + i + " numbers in the sequence.n");
        System.out.println("This are all the numbers in the sequence:");

        for(int j=0;j<i;j++){
            if(j+1==i){
                System.out.print(a[j] + ".");
                break;
            }

            System.out.print(a[j] + ", ");
        }
    }
}

Answer

The problem is not the size of the int[].

Your while loop is constantly checking if a[i] is less than 4000000 while the i variable is already one index ahead. Each loop will have a[i] == 0.

This change will fix the code for you:

int i=1;
while(a[i]<=4000000){
    i++;
    a[i] = a[i-1] + a[i-2];
}


Source: stackoverflow