public class Student {
private String Last_Name;
private String First_Name;
private int Grade_Level, ID;
private double GPA;
public Student() {
Last_Name = "None";
First_Name = "None";
Grade_Level = 0;
GPA = 0.0;
}
public Student(String firstName, String lastName, int gradeLevel, double gpa) {
Last_Name = lastName;
First_Name = firstName;
Grade_Level = gradeLevel;
GPA = gpa;
}
public String toString(){
return Last_Name + ", " + First_Name + "\nGPA: " + GPA + "\nGrade Level: " + Grade_Level + " id # " + ID++;
}
}
我知道每当主函数调用ID值时,它会一次又一次地初始化为0,我已经考虑过使用for循环了但它不起作用,所以如何解决这个问题,谢谢非常感谢你的帮助! 以下是样本运行:
None, None
GPA: 0.0
Grade Level: 0 id # 1
None, None
GPA: 0.0
Grade Level: 0 id # 2
None, None
GPA: 0.0
Grade Level: 0 id # 3
Dovi, Mrs.
GPA: 3.4
Grade Level: 7 id # 4
答案 0 :(得分:3)
您可能正在寻找一个不会改变其状态的实例之间的共享变量,而不管已经创建的对象的数量。这就是静态成员所做的事情:
private static int id;