Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhanced For Loop Exception [duplicate]

Created the below code whilst playing with loops. The code below stores the Fibonacci values into an array and then prints them using for loops.

    int [] numbers;
    numbers = new int[25];

    numbers[0] = 1;
    numbers[1] = 1;
    System.out.println("Initializing the array values");

    for(int i = 2; i < numbers.length; i++)
    {
        numbers[i] = numbers[i-1] + numbers[i-2];
    }

    System.out.println("Printing out Fibonacci values");

    for(int i = 0; i < numbers.length; i++)
    {
        System.out.print(numbers[i] + ", ");
    }

The above code works fine. The first time I threw it together though, I used an enhanced for loop to print out the values (the second for loop in the code). This compiles fine, but when I run it I get the following;

Initializing the array values
Printing out Fibonacci values
1, 1, 2, 3, 8, 34, 377, 17711, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 34
at ArrayDemo.main(ArrayDemo.java:21)

I don't get what went wrong. Changing the second loop shouldn't change the values (you'll notice the fibonacci values are wrong (ie missing values)). And I don't get why a simple enhanced for loop would skip indexes. Now, this isn't really a big deal because this isn't for a project or anything, it just bugs me that I can't figure out why it's doing it. Any clues?

The enhanced for loop just looked like this;

for(int i : numbers)
    {
        System.out.print(numbers[i] + ", ");
    }
like image 975
Rudi Kershaw Avatar asked May 18 '13 11:05

Rudi Kershaw


People also ask

Is it possible with an enhanced for loop to generate an ArrayIndexOutOfBoundsException?

Conclusion. The ArrayIndexOutOfBoundsException in Java usually occurs when we try to access the elements which are greater than the array length. These exceptions can be avoided by using enhanced for loops or proper indices.

Is enhanced for loop same as for-each loop?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.

Which is a limitation of an enhanced for loop?

The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order. Here, you do not have the option to skip any element because it does not work on an index basis. Moreover, you cannot traverse the odd or even elements only.


1 Answers

for(int i : numbers)
{
     System.out.print(numbers[i] + ", ");
}

i here is the elements in the array, not the indexes. It could be bigger than numbers.length.

For example, if numbers = {1,2,3,9} then i will be 1, 2, 3, 9. But its length is 4, so when you loop on the elements inside it, you're trying to do numbers[9] which exceeds its size.

You probably want to System.out.print(i + ", ");

like image 103
Maroun Avatar answered Sep 22 '22 23:09

Maroun