Enhanced for loops are weird. Why does
int size = 10;
Random random = new Random();
int[] scores = new int[size];
for (int score : scores){
scores[score] = random.nextInt(size);
}
System.out.println(Arrays.toString(scores));
Give me a mostly empty array where only the first element is the random number, whilst:
int size = 10;
Random random = new Random();
int[] scores = new int[size];
for (int i = 0; i < scores.length; i++){
scores[i] = random.nextInt(size);
}
System.out.println(Arrays.toString(scores));
gives me what I want: a 10-element array composed of random digits? I thought the two loops were substitutions of each other; but when it comes to the Random(), it's only the first element that gets altered?
Aucun commentaire:
Enregistrer un commentaire