我正在创建一个程序来创建一个名为Student的新类,它设置并获取一些不同的变量。我有一切基本上工作,除非我尝试将正确打印出来的数组元素存储到我的ArrayList中,我得到哈希代码。我肯定会改变一两件小事来修复它,但我最终会在我的智慧中。任何和所有建议都表示赞赏,谢谢!
主:
Student st = new Student();
Student();
}
public static void Student() {
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();
newStudent.getGPA();
newStudent.getEnrolled();
newStudent.getDate();
newStudent.toString();
student[i] = newStudent;
ArrayList myList = new ArrayList();
myList.add(student[i]);
System.out.println(student[i].getName());
System.out.print(student[i].getGPA());
System.out.print(student[i].getEnrolled());
System.out.print(student[i].getDate());
System.out.println(myList);
}
}
学生班:
public class Student {
private String name;
private double gpa;
private boolean enrolled;
private String date;
public Student() {
this.name = "";
this.gpa = 0.0;
this.enrolled = false;
this.date = "none";
}
public Student(String name1) {
this.name = name1;
this.gpa = 0.0;
this.enrolled = false;
this.date = "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) {
this.date = date;
}
public String getDate(){
return this.date;
}
}
答案 0 :(得分:3)
Arrays本身不会使用toString
方法打印其内容。相反,请使用Arrays.toString(yourArrayVar)
或Arrays.deepToString(yourArrayVar)
。
此外,不要忘记覆盖toString
课程中的Student
方法,否则会使用Object#toString
,以此格式打印数据(来自JavaDoc):
getClass()。getName()+&#39; @&#39; + Integer.toHexString(hashCode())
答案 1 :(得分:0)
当您尝试使用此行打印ArrayList
System.out.println(myList);
调用 toString()
。它会尝试将每个项目转换为String
,最终通过toString()
调用Student
。您不会覆盖toString()
,因此您看到的“哈希码”是默认的toString()
from Object
。
根据需要覆盖toString()
以将Student
转换为String
。
@Override
public String toString()
{
// Construct a String here that is appropriate for this class.
// Return it!
}