假设全校有最多400名学生和最多50门课程。现给每个学生的选课清单,要求输出每门课的选课学生名单
时间: 2023-05-30 17:03:26 浏览: 88
这道题可以用一个二维数组来表示每个学生的选课清单,例如:
```
int[][] courses = {
{1, 2, 3}, // 学生1选了课程1、2、3
{2, 4}, // 学生2选了课程2、4
{1, 3, 4}, // 学生3选了课程1、3、4
// ...
};
```
接下来可以用一个HashMap来记录每门课选课的学生名单,例如:
```
HashMap<Integer, ArrayList<Integer>> courseMap = new HashMap<Integer, ArrayList<Integer>>();
```
其中,HashMap的key表示课程编号,value是一个ArrayList,存储该课程选课的学生编号。
最后,遍历每个学生的选课清单,将每个学生加入对应的课程名单中,代码如下:
```
for (int i = 0; i < courses.length; i++) {
for (int j = 0; j < courses[i].length; j++) {
int course = courses[i][j];
ArrayList<Integer> studentList = courseMap.get(course);
if (studentList == null) {
studentList = new ArrayList<Integer>();
courseMap.put(course, studentList);
}
studentList.add(i + 1);
}
}
```
最后输出每门课的选课学生名单,代码如下:
```
for (int i = 1; i <= 50; i++) {
ArrayList<Integer> studentList = courseMap.get(i);
if (studentList != null) {
System.out.print("课程" + i + "选课学生:");
for (int j = 0; j < studentList.size(); j++) {
System.out.print(studentList.get(j) + " ");
}
System.out.println();
}
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)