+ 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

15th Jul 2018, 6:22 PM
Houssam Rachdi
Houssam Rachdi - avatar
2 Respuestas
0
arr[i] = i; should work, I also think a normal for loop would be better
15th Jul 2018, 6:29 PM
TurtleShell
TurtleShell - avatar
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.
15th Jul 2018, 6:51 PM
hinanawi
hinanawi - avatar