0
基於Head First書籍中的一個例子,我遇到了一些麻煩,其中toString方法引起了我的學生問題,他們正在正確輸出uni和home地址。所有我想要做的是輸出如果學生uni地址是空的使用他的家庭地址,否則使用uni one。內部類問題,toString衝突
但我的測試數據如下所示
約翰John72諾丁漢驅動
John72諾丁漢驅動
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";
}
}
}
在每個toString()中也有'\ n'可能也是不可取的。 –
啊不能相信我沒有注意到,我想這就是新鮮的眼睛。謝謝。 – Melky