输入多个学生的成绩信息,包括:学号、姓名、成绩。 学号是每个学生的唯一识别号,互不相同。 姓名可能会存在重复。 使用HashMap存储学生信息,并实现根据学号的检索功能
时间: 2024-03-25 18:39:06 浏览: 30
好的,我可以帮你解决这个问题。首先需要定义一个学生类,包含学号、姓名、成绩三个属性。代码如下:
```
public class Student {
private String id; // 学号
private String name; // 姓名
private int score; // 成绩
public Student(String id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
```
接着,需要创建一个HashMap来存储学生信息,以学号作为键,学生对象作为值。代码如下:
```
Map<String, Student> map = new HashMap<>();
```
然后,输入多个学生的成绩信息,并将其存储到HashMap中。代码如下:
```
// 假设有三个学生信息:学号为001,姓名为张三,成绩为80;学号为002,姓名为李四,成绩为90;学号为003,姓名为王五,成绩为70。
Student s1 = new Student("001", "张三", 80);
Student s2 = new Student("002", "李四", 90);
Student s3 = new Student("003", "王五", 70);
map.put(s1.getId(), s1);
map.put(s2.getId(), s2);
map.put(s3.getId(), s3);
```
最后,实现根据学号的检索功能。代码如下:
```
// 假设要检索学号为002的学生信息
String id = "002";
Student student = map.get(id);
System.out.println(student.getName() + "的成绩是:" + student.getScore());
```
输出结果为:李四的成绩是:90
注意,如果要根据姓名进行检索,则需要遍历HashMap中的每个学生对象,逐一比较姓名属性。如果存在重名的情况,则需要返回多个学生对象。