用Java编写一个,随机选择一个历史美女的代码案例,要求美女数量20个不能重复
时间: 2024-06-11 13:05:51 浏览: 102
/**
* 随机选择一个历史美女的代码案例
* 要求美女数量20个不能重复
*/
import java.util.Random;
public class RandomBeauty {
public static void main(String[] args) {
String[] beauties = {"王昭君", "貂蝉", "杨玉环", "西施", "兰陵王妃", "赵飞燕", "梁山伯与祝英台", "李师师", "秦淮八艳", "花木兰", "孟姜女", "潘金莲", "西门庆", "尉迟恭", "张三丰", "黄飞鸿", "乔峰", "段誉", "虚竹", "杨过"};
Random random = new Random();
int index = random.nextInt(20);
String beauty = beauties[index];
System.out.println("今天您的幸运美女是:" + beauty);
}
}
相关问题
用Java编写一个随机选择历史美女的代码案例,要求美女数量20个,美女名字不能重复,
代码如下:
```java
import java.util.Random;
public class RandomBeautySelector {
public static void main(String[] args) {
String[] beauties = {"西施", "貂蝉", "王昭君", "杨贵妃", "赵飞燕", "花木兰", "祝英台", "慕容芳", "陆小凤", "叶开", "程婴", "苏蓉蓉", "阿珂", "凤九", "韩菱纱", "紫萱", "韩小野", "玉莲", "花无缺", "小龙女"};
Random random = new Random();
String[] selectedBeauties = new String[5]; // 随机选择5个美女
int count = 0;
while (count < 5) {
String beauty = beauties[random.nextInt(beauties.length)];
if (!contains(selectedBeauties, beauty)) { // 确保美女名字不重复
selectedBeauties[count++] = beauty;
}
}
System.out.println("随机选择的历史美女是:");
for (String beauty : selectedBeauties) {
System.out.println(beauty);
}
}
private static boolean contains(String[] arr, String str) {
for (String s : arr) {
if (str.equals(s)) {
return true;
}
}
return false;
}
}
```
该程序运行时,将从20位历史美女中随机选择5位,输出结果如下:
```
随机选择的历史美女是:
叶开
祝英台
紫萱
程婴
苏蓉蓉
```
用Java编写一个随机选择历史美女的代码案例,要求美女数量20个,名字不能重复,不能是男的
public class RandomBeautySelector {
public static void main(String[] args) {
String[] beauties = {"貂蝉", "杨贵妃", "西施", "王昭君", "赵飞燕", "虞姬", "花木兰", "梅艳芳", "张曼玉", "巩俐", "舒淇", "林青霞", "张柏芝", "关之琳", "张国荣", "刘嘉玲", "林志玲", "范冰冰", "李冰冰", "周迅"};
Set<String> selectedBeauties = new HashSet<>();
Random random = new Random();
while (selectedBeauties.size() < 10) {
int index = random.nextInt(20);
String beauty = beauties[index];
if (!selectedBeauties.contains(beauty) && !beauty.startsWith("男")) {
selectedBeauties.add(beauty);
}
}
System.out.println("今天的美女有:");
for (String beauty : selectedBeauties) {
System.out.println(beauty);
}
}
}
阅读全文