public class Demo4 {
public static void main(String args[]) {
Random random = new Random();
int r = random.nextInt(20) + 1;
// 创建一个集合对象
HashSet<Integer> list = new HashSet<>();
// 循环判断集合大小为10
while (true) {
if (list.size() <= 9) {
r = random.nextInt(20) + 1;
list.add(r);
} else {
break;
}
}
// 遍历打印10个随机数
for (Integer i : list) {
System.out.print(i+",");
}
public class test {
public static void main(String[] args) {
Random ran = new Random();
int[] arr = new int[20];
int count = 0;
flag:while (true) {
int num = ran.nextInt(20) + 1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) {
continue flag;
}
}
arr[count] = num;
count++;
if (count == arr.length) {
break;
}
}
System.out.println(Arrays.toString(arr));
}
}