【发布时间】:2014-05-01 07:01:48
【问题描述】:
我想使用 Math.random 生成 6 个不同的随机数并将它们全部存储到一个数组中。我怎样才能确保它们是不同的?到目前为止我只有这个,这有一个错误。我只需要 1 到 49 之间的数字。( 1 + (int) (Math.random() * 49) )。
public static void main (String []args) {
int []randomNumArray = new int [6];
randomNumArray[0] = randomNumber();
System.out.println(randomNumArray[0]);
for (int i = 1; i < 6; i++) {
for (int j = 0; j < i; j++) {
randomNumArray[i] = randomNumber();
do {
if (randomNumArray[i] == randomNumArray[j]) {
randomNumArray[i] = randomNumber();
}
} while(randomNumArray[i] == randomNumArray[j]);
}
System.out.println(randomNumArray[i]);
}
}
//This method is for generating random numbers
public static int randomNumber (){
return ( 1 + (int) (Math.random() * 49) );
}
【问题讨论】:
-
您提到您的代码有错误。它究竟是如何表现出来的?
-
对数组进行洗牌是获得非重复元素的好方法。你为什么不想使用它?
-
当我运行这段代码时,数组仍然有重复@merlin2011
-
应该只是编辑这个问题而不是开始一个新问题:stackoverflow.com/questions/22584244/…