Why does think not work? It just prints zeros. However it works when I use a normal for loop with an index value ‘i’ and using ‘a[i]’ inside the body of the loop.
The problem is not with the printing loop, as it does not print the values, even with a normal for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] a = new int[5];
for (int i : a)
{
System.out.println("Enter number : ");
i=s.nextInt();
}
System.out.println("\nThe numbers you entered are : \n");
for (int i : a)
{
System.out.println(i);
}
}
}
When you access the element using enhanced for-loop: –
Here,
int iis a copy of element in the array. When you modify it, the change will not get reflected in the array. That’s why the array elements are 0.So, you need to iterate using traditional for-loop and access the array elements on that
indexto assign values to it.Even if your array was an array of some reference, it would still not work. That’s because, the variable in a for-each is not a proxy for an array or Collection reference. For-each assigns each entry in the array to the variable in the loop.
So, your
enhanced for-loop: –is converted to: –
So, the initialization of
iin the loop, is not reflected in the array. And thus the array elements arenull.Workarond: –
use traditional for loop: –