2. 学生进行选课,请统计出每个学生的选课门数,及每门课选修的人数。输入格式: 学生学号 选修课程 学生学号 选修课程…(中间用空格隔开,学生学号输入000代表结束)输出格式: 学生学号 选修门数 课程1 选修人数 课程2 选修人数
时间: 2023-11-10 11:10:46 浏览: 32
很高兴能为您解答问题。
根据您提供的问题,可以使用HashMap来进行统计。代码如下:
```java
import java.util.*;
public class CourseSelection {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, Map<String, Integer>> studentCourseMap = new HashMap<>();
String studentId = "";
while (!"000".equals(studentId = scanner.next())) {
String course = scanner.next();
Map<String, Integer> courseStudentMap = studentCourseMap.getOrDefault(studentId, new HashMap<>());
Integer count = courseStudentMap.getOrDefault(course, 0);
courseStudentMap.put(course, count + 1);
studentCourseMap.put(studentId, courseStudentMap);
}
for (Map.Entry<String, Map<String, Integer>> entry : studentCourseMap.entrySet()) {
String studentIdKey = entry.getKey();
Map<String, Integer> courseStudentMapValue = entry.getValue();
int courseCount = courseStudentMapValue.size();
System.out.print(studentIdKey + " " + courseCount);
for (Map.Entry<String, Integer> courseCountEntry : courseStudentMapValue.entrySet()) {
String courseName = courseCountEntry.getKey();
int studentCount = courseCountEntry.getValue();
System.out.print(" " + courseName + " " + studentCount);
}
System.out.println();
}
}
}
```
输入样例:
```
001 math 001 history 002 math 002 english 003 biology 003 history 003 math 001 biology 000
```
输出样例:
```
001 2 math 1 history 1 biology 1
002 2 math 1 english 1
003 3 biology 1 history 1 math 1
```
希望能够解决您的问题,如果还有其他问题,可以继续提问哦!