根据《 Head First》一书中的例子,我遇到了一些麻烦,其中toString方法导致我的学生出现问题,并且它们是uni且正确输出了家庭住址。如果学生的uni地址为空,我想做的就是输出,使用他的家庭住址,否则使用uni。

但是我的测试数据如下


  约翰·约翰诺丁汉径72号
  
  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";
    }
}


}

最佳答案

您的getHomeAddress方法负责显示uni地址,因此此行:

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


可以缩短为:

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


否则,您的getHomeAddress方法将提取uni地址,然后您的getUniAddress方法将再次提取uni地址。

同样在您的地址toString中,您拉的是该人的姓名,并且您可能不是故意的(并且您可能也不想在这里使用换行符,因为您的其他toString方法中有换行符)。

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

关于java - 内部类麻烦,toString冲突,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13313222/

10-11 14:16