我想通过使用Math.random生成6个不同的随机数,并将它们全部存储到数组中。我怎样才能确保它们与众不同?到目前为止我只有这个,这有一个bug。我只需要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) );
}
答案 0 :(得分:3)
生成随机数并继续将它们添加到Set中,直到其大小= 6.集合只能包含唯一元素。所以,你确保独一无二。
编辑:
public static void main(String[] args) {
Set<Integer> intSet = new LinkedHashSet<Integer>();
Random r = new Random();
while (intSet.size() <= 6) {
intSet.add(r.nextInt(49)); // or your method of generating random numbers
}
System.out.println(intSet);
}
答案 1 :(得分:0)
显然,set
方法和洗牌是更有效的方法,但考虑到上下文,这里是OP代码的修改,以实现唯一性,解决&#34; bug& #34;在他的代码中。
import java.util.*;
public class Main {
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++)
{
int candidate;
boolean foundMatch;
do
{
candidate = randomNumber();
foundMatch = false;
for (int j = 0; j < i; j++)
if (candidate == randomNumArray[j])
foundMatch = true;
} while (foundMatch);
randomNumArray[i] = candidate;
System.out.println(randomNumArray[i]);
}
}
//This method is for generating random numbers
public static int randomNumber (){
return ( 1 + (int) (Math.random() * 49) );
}
}