实现Java中利用数组随机抽取幸运观众,可以按照以下步骤操作:
准备工作
- 定义一个数组,存储所有的观众名单;
- 引入Random类,生成随机数;
- 定义一个变量或常量,存储抽取的人数。
String[] audiences = {"张三", "李四", "王五", "赵六", "钱七", "孙八"};
Random random = new Random();
final int LUCKY_NUMBER = 3;
随机抽取幸运观众
- 定义一个新的数组,存储被抽中的观众;
- 利用for循环,在数组中随机抽取幸运观众,并将其存储到新的数组中;
- 输出被抽中的观众名单。
String[] luckyAudiences = new String[LUCKY_NUMBER];
for (int i = 0; i < LUCKY_NUMBER; i++) {
int randomIndex = random.nextInt(audiences.length);
luckyAudiences[i] = audiences[randomIndex];
}
System.out.println("幸运观众名单:");
for (String audience : luckyAudiences) {
System.out.println(audience);
}
示例说明
以下为两个示例说明,分别演示了随机抽取1名和5名幸运观众的过程:
示例1:抽取1名
String[] audiences = {"张三", "李四", "王五", "赵六", "钱七", "孙八"};
Random random = new Random();
final int LUCKY_NUMBER = 1;
String[] luckyAudiences = new String[LUCKY_NUMBER];
for (int i = 0; i < LUCKY_NUMBER; i++) {
int randomIndex = random.nextInt(audiences.length);
luckyAudiences[i] = audiences[randomIndex];
}
System.out.println("幸运观众名单:");
for (String audience : luckyAudiences) {
System.out.println(audience);
}
运行结果:
幸运观众名单:
赵六
示例2:抽取5名
String[] audiences = {"张三", "李四", "王五", "赵六", "钱七", "孙八"};
Random random = new Random();
final int LUCKY_NUMBER = 5;
String[] luckyAudiences = new String[LUCKY_NUMBER];
for (int i = 0; i < LUCKY_NUMBER; i++) {
int randomIndex = random.nextInt(audiences.length);
luckyAudiences[i] = audiences[randomIndex];
}
System.out.println("幸运观众名单:");
for (String audience : luckyAudiences) {
System.out.println(audience);
}
运行结果:
幸运观众名单:
钱七
孙八
赵六
孙八
李四
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java利用数组随机抽取幸运观众 - Python技术站