java数据结构使用哈希表创建一个学生信息 (学号、专业、名字、成绩),当输入学号时,要求查找到该学生所有信息。
时间: 2023-05-22 18:06:47 浏览: 91
好的,以下是使用Java哈希表创建学生信息的示例代码:
import java.util.HashMap;
public class Student {
private int ID;
private String major;
private String name;
private double score;
public Student(int id, String major, String name, double score) {
this.ID = id;
this.major = major;
this.name = name;
this.score = score;
}
public int getID() {
return ID;
}
public String getMajor() {
return major;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public static void main(String[] args) {
HashMap<Integer, Student> studentMap = new HashMap<>();
Student s1 = new Student(1001, "Computer Science", "Tom", 89.5);
Student s2 = new Student(1002, "Mathematics", "Jerry", 92.0);
Student s3 = new Student(1003, "Physics", "Alice", 85.0);
studentMap.put(s1.getID(), s1);
studentMap.put(s2.getID(), s2);
studentMap.put(s3.getID(), s3);
int searchID = 1002;
if (studentMap.containsKey(searchID)) {
Student searchStudent = studentMap.get(searchID);
System.out.println("ID: " + searchStudent.getID() + ", Major: " + searchStudent.getMajor() + ", Name: " + searchStudent.getName() + ", Score: " + searchStudent.getScore());
} else {
System.out.println("The student with ID " + searchID + " is not found!");
}
}
}
当输入学号时,程序会查找哈希表中是否包含该学号的学生信息,如果存在则输出学生的所有信息,否则提示未找到该学生。
阅读全文