2012-11-09 68 views
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"; 
    } 
} 

}

回答

3

getHomeAddress方法負責顯示的單地址,所以這行:

return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n"; 

可以縮短爲:

return getName() + " " + getHomeAddress() + " " + "\n"; 

否則你getHomeAddress方法將拉動單地址,那麼你的getUniAddress方法將再次拉出uni地址。

同樣在你的地址toString你拉的人的名字,你可能並不是故意的(因爲你在其他toString方法有一個換行符,你可能不希望在這裏換行)。

@Override 
public String toString(){ 
    return number + " " + street; 
} 
+1

在每個toString()中也有'\ n'可能也是不可取的。 –

+0

啊不能相信我沒有注意到,我想這就是新鮮的眼睛。謝謝。 – Melky