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]);
}
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With