У меня есть метод, который работает неправильно. Метод должен сортировать набор чисел от 1 до 20 случайным образом (каждый номер должен появляться только один раз). Моя проблема в том, что когда я запускаю программу, некоторые числа повторяются несколько раз. код выглядит следующим образом:Проблема со случайным методом
public static int randomize(int index) {
//This array will hold the 20 numbers.
int[] randomIndex = new int[20];
Random ranNum = new Random();
for (int x = 0; x<20; x++) {
int temp;
//The number is generated randomly and saved in temp.
temp = ranNum.nextInt(20);
//This loop skips the first index.
if (x != 0){
/*Here, the loop is supposed to compare a generated number with
the previous one*/
for (int y = 1; y<=x; y++) {
while(temp == randomIndex[x-y]) {
/*If the while loop finds that temp variable matches any previous
number it will generate another random number for it until it finds
no matches.*/
temp = ranNum.nextInt(20);
}
}
}
/*Once no match has been found for temp, the number is assigned to an index,
and the loop is executed with a x variable increment.
randomIndex[x] = temp;
}
//Finally the array with the set of random numbers is sent to the main function.
return randomIndex[index];
}
И я получил следующий вывод:
19, 19, 5, 16, 6, 2, 18, 1, 15, 1, 5, 19, 11, 4, 18, 0, 5, 18, 10.
Так что теперь я понятия не имею, что делать. : C
Не могли бы вы добавить комментарии о том, что ваш код * предполагается * делать? Я думаю, что это также поможет вам в отладке! –
Почему бы не использовать метод 'List' и' Collections.shuffle() '? –
Или, по крайней мере, добавить каждый номер, который вы уже нарисовали в списке, и проверить, является ли это дубликат с List.contains (newNumber)? – sheltem