0

我正在制作一个程序,该程序创建一个名为 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;
}
 }
4

2 回答 2

3

数组本身不会使用toString方法打印它们的内容。相反,使用Arrays.toString(yourArrayVar)or Arrays.deepToString(yourArrayVar)

另外,不要忘记覆盖类中的toString方法Student,否则它将使用Object#toString, 结束以这种格式打印数据(来自 JavaDoc):

getClass().getName() + '@' + Integer.toHexString(hashCode())

于 2013-11-08T16:58:19.443 回答
0

当您尝试ArrayList使用此行打印 ,

System.out.println(myList);

toString()叫做。它尝试将其每个项目转换为String(最终)调用toString()您的Student. 您没有覆盖toString(),因此您看到的“哈希码”是toString()来自Object的默认值。

覆盖toString()以将您Student的转换String为适当的。

@Override
public String toString()
{
    // Construct a String here that is appropriate for this class.
    // Return it!
}
于 2013-11-08T17:03:16.437 回答