我正在进行一项任务,我必须在屏幕上实例化几个不同的对象并对其进行格式化。我无法正确输出字符串;代替文本我得到像这样的输出
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;
}
}
我做错了什么?`
答案 0 :(得分:1)
这是因为您正在尝试打印对象(student1)而不是对象的属性。
请尝试:
的System.out.println(student1.getFirstName()+ “\ t” 的+ student1.getLastName()+ “\ t” 的+ student1.getStudentIdNumber());
而不是:
System.out.println(student1);
希望这能解决您的问题。
答案 1 :(得分:0)
您需要输出如下:
System.out.println(student1.getFirstName() + " " + student1.getLastName());
答案 2 :(得分: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()方法。