0

这是我编写的一个包含地址信息的构造函数,但我在最后一部分遇到了问题,我必须返回一个包含名称、地址、城市、州邮政编码的字符串。写它的正确方法是什么?

公共类地址{

private String name;
private String address;
private String state;
private String city;
private String zipcode;

public Address(String name, String address, String state, String city, String zipcode){

    this.name = name;
    this.address = address;
    this.state = state;
    this.city = city;
    this.zipcode = zipcode;


}

public Address(){

    name = "occupant";
    address = " ";
    state = " ";
    city = " ";
    zipcode = " ";


}

public void setAddress(String Address){

    this.address = Address;

}

public void setstate(String state){

    this.state= state;


}

public void setcity(String city){

    this.city = city;
}

public void setzipcode(String code){

   this.zipcode = code; 

}

public String getaddress(){  // Return string that contains name and address and city and zipcode

    return getaddress() + " " + return state + " " + return city + " " + return code;



}

}

4

3 回答 3

3
 return address + " " + state + " " + city + " " + code;

几点注意事项:

  • 只有一个return,后面是要返回的对象,是字符串拼接的结果
  • 调用您的连接方法getFullAddress()以将其与 getter 区分开来。
  • 使用小写的变量名
  • getter 和 setter 应该得到 camel-case: setCity()getState()
于 2012-04-04T21:50:10.653 回答
1

为了清楚起见,我将变量地址重命名为街道。无论如何,我不会重写,而是toString()在每个字段上添加 getter,并添加一个静态实用程序类以使用以下方法打印地址

static String formatAddress(Address address){
    final String formatter = "Address\n%s\n%s\n%s, %s  %s";
    return String.format(formatter, address.getName(),address.getAddress(),address.getCity(), address.getState(), address.getZipcode());
}
于 2012-04-04T22:04:33.710 回答
0

我认为您的问题可能是您在getaddress()内部调用getaddress()而不是使用address

编辑:正如 Bozho 指出的那样,方法中的每个语句只有一个返回值。

于 2012-04-04T21:51:45.680 回答