+ 1
Initialize an array with an enhanced for loop
I have a problem with this code , I want to Initialize an array with an enhanced for loop but i have a different result than what i was expecting; public class Main { public static void main(String[] args) { int arr[]=new int [4]; int i= 0; for (int x : arr) { arr[x]=i; i++; } for (int j = 0; j < 4; j++) { System.out.println(arr[j]); } } } the result was 3 0 0 0
2 Respuestas
0
arr[i] = i; should work, I also think a normal for loop would be better
0
i agree with TurtleShell here, doing this results in only the first element getting assigned to as arr[x] will always be 0 since the array is not initialized with values.