我有一个方法无法正常工作。 该方法应该将一组数字从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