user3357525
user3357525

Reputation: 11

Multi-Dimensional Array Index Out of Bounds Java

I need help with figuring out what exactly is wrong with this code:

public class Fibonacci
{
    public static void main(String args[])
    {
        int[][] numbers;
        numbers = new int[1][25];
        numbers[0][0] = 0;
        numbers[0][1] = 1;
        System.out.println("Fibonacci series: \n");
        System.out.println(numbers[0][0]);
        System.out.println(numbers[0][1]);

        for(int i=2; i < 20; i++)
        {
            numbers[1][i] = numbers[0][i-2] + numbers[0][i-1];
            System.out.println(numbers[1][i]);
        }
    }
}

I'm getting this error:

   Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
        at Fibonacci.main(Fibonacci.java:15)

I can see that my array index is out of bounds on line 15, but I don't know how to fix it. :/ Help appreciated. :) P.S. New here

Upvotes: 1

Views: 764

Answers (3)

Kick
Kick

Reputation: 4923

The two dimensinal array is numbers = new int[1][25]; first dimension size is 1 , it mean you can access the element or set the value using index 0.So change the code from numbers[1][i] to numbers[0][i]

Upvotes: 0

WillfulWizard
WillfulWizard

Reputation: 5409

In short, your array is not big enough.

You declare your array as "new int[1][25]", which means, because of [1], only a single row. But then on line 15 you reference the second row: "numbers[1][i]".

There is clearly more wrong with your code based on your class name of Fibonacci, but the solution to your immediate problem is to make your array larger: "new int[X][25]" but put in something bigger for X.

Upvotes: 0

Embattled Swag
Embattled Swag

Reputation: 1469

You have numbers[1][i] both in lines 15 and 16, but that throws an exception because the size of the first dimension is only 1. Try changing both to numbers[0][i].

Or, from what it looks like you're trying to do you can alter your initialization of your array to

numbers = new int[2][25];

Upvotes: 4

Related Questions