Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhanced 'for' loop causes an ArrayIndexOutOfBoundsException

Tags:

java

loops

Here's my code:

import java.util.Scanner;

public class Arrays {
    public static void main(String[] args) {
        Arrays psvm = new Arrays();
        psvm.start();
    }

    public void start() {
        Scanner ben = new Scanner(System.in);
        int[] arr = new int[4];
        int[] arrs = new int[4];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = ben.nextInt();
        }
        check(arr, arrs);
    }

    public void check(int arr[], int arrs[]) {
        for (int i = 0; i < arr.length; i++) {
            arrs[i] = arr[i];
        }
        for (int i : arrs) {
            System.out.println(arrs[i]);
        }
    }
}

The enhanced for loop gives ArrayIndexOutOfBoundsException:

for (int i : arrs) {
    System.out.println(arrs[i]);
}

While this for loop statement works. Why? What's wrong with the code?

for (int i = 0; i < arrs.length; i++) {
    System.out.println(arrs[i]);
}
like image 882
Mob Avatar asked Jan 25 '26 06:01

Mob


1 Answers

In this case, i will be assigned to each element in the array - it is not an index into the array.

What you want to do is:

for(int i : arrs)
{
    System.out.println(i);
}

In your code, you're trying to select the integer at the array index referenced by the iteration object. In other words, your code is equivalent to:

for(int idx = 0; idx < arrs.length; idx++)
{
    int i = arrs[idx];
    System.out.println(arrs[i]);
}
like image 93
Edward Thomson Avatar answered Jan 27 '26 19:01

Edward Thomson