所以我在这里创建了一个代码,它创建了一个名为student的对象,它接受名称和专业的字符串,并跟踪总积分和质量点来计算GPA。我正在尝试创建一个HashMap,以便能够使用密钥(学生ID)搜索学生并获取使用Student蓝图类保存的值。但我的代码是为所有键分配相同的值,最后一个学生进入HashMap。这是当前输出后面的代码。请注意,这是我完整代码的简化版本,只是为了展示我遇到的问题。感谢愿意提供帮助的任何人!
import java.util.HashMap;
public class Test {
public static class Student {
static private String name;
static private String major;
static private int totalCredits;
static private int totalQP;
public Student (String name, String major) {
this.name = name;
this.major = major;
this.totalCredits = 0;
this.totalQP = 0;
}
public static void courseCompleted (int grade, int creditHours) {
totalQP += grade;
totalCredits += creditHours;
}
@Override
public String toString () {
float GPA;
if (totalCredits != 0) {
GPA = (float) totalQP/totalCredits;
} else {
GPA = (float) 4.0;
}
return "Student name: " + name + "\nStudent Major: " + major
+ "\nStudent GPA: " + GPA;
}
}
public static void main (String [] args) {
HashMap<Integer, Student> studentDatabase = new HashMap();
studentDatabase.put(1234, new Student("Default", "Default"));
studentDatabase.put(7623, new Student("Phyllis Jones", "English"));
studentDatabase.put(8729, new Student("Cletus Smith", "History"));
studentDatabase.put(7321, new Student("Betty Booth", "Computer Science"));
studentDatabase.put(3242, new Student("Samuel Seybright", "History"));
studentDatabase.put(9823, new Student("Oscar Blue", "English"));
studentDatabase.put(2341, new Student("Sally Grief", "Copmputer Science"));
studentDatabase.put(8321, new Student("Jacques Matchel", "Mathematics"));
System.out.println(studentDatabase.entrySet());
}
}
输出: [8321 =学生姓名:Jacques Matchel 学生专业:数学 学生GPA:4.0,1234 =学生姓名:Jacques Matchel 学生专业:数学 学生GPA:4.0,2341 =学生姓名:Jacques Matchel 学生专业:数学 学生GPA:4.0,7623 =学生姓名:Jacques Matchel 学生专业:数学 学生GPA:4.0,8729 =学生姓名:Jacques Matchel 学生专业:数学 学生GPA:4.0,7321 =学生姓名:Jacques Matchel 学生专业:数学 学生GPA:4.0,3242 =学生姓名:Jacques Matchel 学生专业:数学 学生GPA:4.0,9823 =学生姓名:Jacques Matchel 学生专业:数学 学生GPA:4.0]