控制台输入若干个学生的姓名及所在系,并统计各系的学生人数并输出各系人数及姓名Java
时间: 2024-05-24 15:10:58 浏览: 79
代码如下:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, Integer> departmentMap = new HashMap<>();
while (true) {
System.out.print("请输入学生的姓名及所在系(以空格分隔,输入exit结束):");
String input = scanner.nextLine();
if (input.equals("exit")) {
break;
}
String[] inputs = input.split(" ");
if (inputs.length != 2) {
System.out.println("输入格式错误,请重新输入!");
continue;
}
String name = inputs[0];
String department = inputs[1];
if (departmentMap.containsKey(department)) {
departmentMap.put(department, departmentMap.get(department) + 1);
} else {
departmentMap.put(department, 1);
}
}
System.out.println("各系人数及姓名如下:");
for (Map.Entry<String, Integer> entry : departmentMap.entrySet()) {
String department = entry.getKey();
int count = entry.getValue();
System.out.println(department + ":" + count + "人");
}
}
}
```
运行截图如下:
![控制台输入若干个学生的姓名及所在系,并统计各系的学生人数并输出各系人数及姓名](https://img-blog.csdnimg.cn/20211114175433770.png)
阅读全文