在使用Java生成随机数时,这里有两种方式:
①是使用Set的不可重复性,来生成的,下面我们来看代码:
public class RandomTest{
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
Random rand = new Random();
int index = 0;
while (true) {
int s = rand.nextInt(33)+1;
if (set.contains(s)) {
s = rand.nextInt(33)+1;
}else{
set.add(s);
index++;
}
if (index == 6) {
break;
}
}
for (Integer integer : set) {
System.out.print(integer +",");
}
System.out.println();
}
② 是通过boolean来判断当前的元素是否插入到集合中了
public class RandomTest{
public static void main(String[] args) {
ArrayList<Integer> red = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < 6; i++) {
int s = rand.nextInt(33) + 1;
if (CunZai(red, s)) {
red.add(s);
}else{
//这里注意,必须得i--,要不然,集合中如果有重复的元素就会空位置,必须让它回退到前一个重新生成
i--;
}
}
}
public static boolean CunZai(ArrayList<Integer> arr ,int i){
for (int j = 0; j < arr.size(); j++) {
if (arr.get(j) == i) {
return false;
}
}
return true;
}
}
运行结果: