用Java编写一个随机选择历史美女的代码案例,要求美女数量20个,美女名字不能重复,
时间: 2024-06-11 20:05:50 浏览: 101
代码如下:
```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位,输出结果如下:
```
随机选择的历史美女是:
叶开
祝英台
紫萱
程婴
苏蓉蓉
```
阅读全文