基于 Head First 书籍示例之一,我遇到了一些麻烦,其中 toString 方法导致我的学生出现问题,并且它们是正确输出的 uni 和家庭地址。我要做的就是输出如果学生的大学地址为空,则使用他的家庭地址,否则使用大学地址。
但我的测试数据如下所示
约翰·约翰诺丁汉大道 72 号
约翰诺丁汉大道 72 号
public class Test {
public static void main(String[] args){
Student student1 = new Student("John", 19, "Walkers Way");
student1.setUniAddress(72, "Nottingham Drive");
System.out.print(student1.toString());
}
}
其他类
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet){
this.name = name;
this.homeAddress = new Address(houseNumber, homeStreet);
}
public String getName() { return this.name; }
public Address getHomeAddress(){
if(this.uniAddress == null){
return this.homeAddress;
}else{
return getUniAddress();//this.uniAddress;
}
}
public Address getUniAddress() { return this.uniAddress; }
public void setUniAddress(int number, String add){
Address address = new Address(number, add);
uniAddress = address;
}
@Override
public String toString(){
return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n";
}
public class Address{
private int number;
private String street;
public Address(int no, String street){
this.number = no;
this.street = street;
}
@Override
public String toString(){
return name + number + " " + street + "\n";
}
}
}