【发布时间】:2014-01-29 00:39:40
【问题描述】:
我的方法不能正常工作。 该方法应该对一组数字从 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
【问题讨论】:
-
能否请您添加有关您的代码应该做什么的cmets?我想这对你调试也有帮助!
-
为什么不使用
List和Collections.shuffle()方法? -
或者至少将您已经绘制的每个数字添加到列表中,并使用 List.contains(newNumber) 检查它是否重复?
-
您的主要问题是您只确保您正在使用的号码一次在列表中,这意味着您实际上并没有检查以确保它在整个列表..
标签: java algorithm sorting methods random