如何在屏幕上获取输出对象?

问题描述 投票:1回答:3

我正在进行一项任务,我必须实例化几个不同的对象并在屏幕上格式化它们。我无法正确输出字符串;代替文本我得到这样的输出

run:
First Name  Last Name   Student ID Number   
studentdemo.StudentDemo@6d06d69c
studentdemo.StudentDemo@7852e922
studentdemo.StudentDemo@4e25154f
studentdemo.StudentDemo@70dea4e
studentdemo.StudentDemo@5c647e05
BUILD SUCCESSFUL (total time: 0 seconds)

这是我的主要内容

package studentdemo;
public class MainStudent {public static void main(String[] args) {
StudentDemo student1 = new StudentDemo("Peter\t","Adams\t","123546\t");
StudentDemo student2 = new StudentDemo("James\t","Clark\t","654332\t");
StudentDemo student3 = new 
StudentDemo("Christopher\t","Colombo\t","223344\t");
StudentDemo student4 = new StudentDemo("Amy\t","Tan\t","997766\t");
StudentDemo student5 = new 
StudentDemo("Marry\t","Madison\t","6543321\t");
System.out.println("First Name\t"+"Last Name\t"+"Student ID Number\t");
System.out.println(student1);
System.out.println(student2);
System.out.println(student3);
System.out.println(student4);
System.out.println(student5);

}

}

这是我的另一堂课

package studentdemo;
public class StudentDemo {
private String firstName;
private String lastName;
private String studentIdNumber;

public StudentDemo(String firstName, String lastName, String 
studentIdNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.studentIdNumber = studentIdNumber;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getFirstName() {
return firstName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getLastName() {
    return lastName;
}
public void setStudentIdNubmer(String studentIdNumber) {
    this.studentIdNumber = studentIdNumber;
}
public String getStudentIdNumber() {
    return studentIdNumber;
}
}

我做错了什么?`

java object constructor
3个回答
1
投票

这是因为您尝试打印对象(student1)而不是对象的属性。

请试试:

的System.out.println(student1.getFirstName()+ “\ t” 的+ student1.getLastName()+ “\ t” 的+ student1.getStudentIdNumber());

代替:

System.out.println(student1);

希望这能解决你的问题。


0
投票

您需要像这样输出:

System.out.println(student1.getFirstName() + " " + student1.getLastName());

0
投票

更好的解决方案是覆盖StudentDemo类中的toString()方法。例如:

public class StudentDemo {
    ...
    @Override
    public String toString() {
        return this.firstName + " " + this.lastName + " " + this.studentIdNumber;
    }
}

现在当你创建一个新的学生对象,即StudentDemo student1 = new StudentDemo();时,如果你做System.out.prntln(student1);,将自动调用toString()方法。

© www.soinside.com 2019 - 2024. All rights reserved.