我创建了一个名为Student的新类程序,它设置并获取不同的变量,如名称,GPA,如果它们已注册以及何时注册(这是一个字符串,它的目的是)。问题是,当我尝试将信息存储到数组和/或数组列表并打印它时,我得到打印的哈希码而不是信息。该程序并不完全,但我试图首先解决哈希码问题。如果你能提供帮助我会非常感激。提前谢谢!
Student st = new Student();
System.out.println(st.getName());
Student1();
Student st1 = new Student("John");
}
public static void Student1() {
System.out.println("Enter the data for student 1 :");
Student st = new Student();
Scanner keyboard = new Scanner(System.in);
String name = keyboard.next();
double GPA = keyboard.nextDouble();
boolean enrolled = keyboard.nextBoolean();
String date = keyboard.next();
for (int i =0; i<5; i++){
Student newStudent = new Student();
newStudent.setName(name);
newStudent.setGPA(GPA);
newStudent.setEnrolled(enrolled);
newStudent.setDate(date);
ArrayList <Student> strList = new ArrayList<Student>();
Student student[] = new Student[5];
newStudent.getName();
student[i] = newStudent;
strList.add(newStudent);
System.out.println(student[i]);
}
学生班
公共班学生{
private String name;
private double gpa;
private boolean enrolled;
private String enrollDate;
public Student() {
this.name = "";
this.gpa = 0.0;
this.enrolled = false;
this.enrollDate = "none";
}
public Student(String name1) {
this.name = name1;
this.gpa = 0.0;
this.enrolled = false;
this.enrollDate = "none";
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setGPA(double gpa) {
this.gpa = gpa;
}
public double getGPA() {
return this.gpa;
}
public void setEnrolled(boolean enrolled) {
this.enrolled = enrolled;
}
public boolean getEnrolled() {
return this.enrolled;
}
public void setDate(String date) {
}
}
答案 0 :(得分:2)
这是因为您将学生对象放入数组中:
Student student[] = new Student[5];
newStudent.getName();
student[i] = newStudent;
strList.add(newStudent);
System.out.println(student[i]);
在您打印时,您不打印学生姓名,而是打印对象本身。无论何时在对象上执行System.out.println,都会返回哈希码。
这是你的问题吗?
答案 1 :(得分:1)
toString()
。如果不这样做,JVM中的默认值就是打印哈希码。System.out.println(student[i].getName());
Arrays.toString()
。答案 2 :(得分:0)
请覆盖toString()方法,因为它目前只打印Object类中默认的toString()方法实现,该方法设置为当前对象的hashcode()。
答案 3 :(得分:-1)
这种打印将获取实例地址而不是它的打印。
因为您想要打印参考类型,所以VM不知道您希望它如何显示,或者某些字段不能用于打印。
它适合你,Overriding&#34; public String toString()&#34;方法并实现自己的格式。