Java – enhanced ‘for’ loop causes ArrayIndexOutOfBoundsException
•
Java
This is 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 an ArrayIndexOutOfBoundsException:
for (int i : arrs) {
System.out.println(arrs[i]);
}
Although this for loop statement is valid Why? What's wrong with the code?
for (int i = 0; i < arrs.length; i++) {
System.out.println(arrs[i]);
}
Solution
In this case, I will be assigned to each element in the array - it is not the index of the array
What you want to do is:
for(int i : arrs)
{
System.out.println(i);
}
In your code, you try to select an 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]);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
