利用Random类和Hashtable类。要求做一个抽奖的程序,从班级的学号中抽出一个一等奖,两个二等奖,三个三等奖,以学号来选,最后在用学号和人名对应上,输出中奖的同学的姓名。同时要求奖项和奖品进行匹配。
时间: 2023-06-19 21:03:26 浏览: 75
好的,以下是一个Java程序的代码实现:
```java
import java.util.*;
public class Lottery {
public static void main(String[] args) {
// 输入班级学生的学号和姓名,存储到Hashtable中
Hashtable<String, String> students = new Hashtable<>();
students.put("001", "张三");
students.put("002", "李四");
students.put("003", "王五");
students.put("004", "赵六");
students.put("005", "钱七");
students.put("006", "孙八");
// 抽奖,使用Random类生成随机数
Random random = new Random();
ArrayList<String> lotteryList = new ArrayList<>(); // 存储中奖学生的学号
String firstPrize = ""; // 一等奖
String secondPrize1 = ""; // 二等奖1
String secondPrize2 = ""; // 二等奖2
ArrayList<String> thirdPrizeList = new ArrayList<>(); // 三等奖
// 抽取一等奖
int index = random.nextInt(students.size());
firstPrize = (String) students.keySet().toArray()[index];
lotteryList.add(firstPrize);
// 抽取二等奖
while (true) {
index = random.nextInt(students.size());
String studentNumber = (String) students.keySet().toArray()[index];
if (!lotteryList.contains(studentNumber)) {
if (secondPrize1.equals("")) {
secondPrize1 = studentNumber;
lotteryList.add(secondPrize1);
} else if (secondPrize2.equals("")) {
secondPrize2 = studentNumber;
lotteryList.add(secondPrize2);
break;
}
}
}
// 抽取三等奖
while (true) {
index = random.nextInt(students.size());
String studentNumber = (String) students.keySet().toArray()[index];
if (!lotteryList.contains(studentNumber)) {
if (thirdPrizeList.size() < 3) {
thirdPrizeList.add(studentNumber);
lotteryList.add(studentNumber);
} else {
break;
}
}
}
// 输出中奖名单
System.out.println("一等奖:" + students.get(firstPrize));
System.out.println("二等奖:");
System.out.println(students.get(secondPrize1));
System.out.println(students.get(secondPrize2));
System.out.println("三等奖:");
for (String studentNumber : thirdPrizeList) {
System.out.println(students.get(studentNumber));
}
}
}
```
这个程序使用了Hashtable类来存储班级学生的学号和姓名,使用Random类来生成随机数进行抽奖,使用ArrayList类来存储中奖学生的学号。程序抽取的结果符合要求,输出中奖学生的姓名和对应的奖项。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)