这是我写的一个包含地址信息的构造函数,但是我在最后一部分遇到了麻烦,我必须返回一个包含名称,地址,城市,州邮政编码的字符串。写它的正确方法是什么?
公共类地址{
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;
}
}
答案 0 :(得分:3)
return address + " " + state + " " + city + " " + code;
一些注意事项:
return
,后跟要返回的对象,这是字符串连接的结果getFullAddress()
,以区别于getter。setCity()
,getState()
答案 1 :(得分:0)
我认为您的问题可能是您在getaddress()
内拨打getaddress()
而不是使用address
编辑:正如Bozho指出的那样,方法中每个语句只返回一次。
答案 2 :(得分:0)
为了清楚起见,我会将变量地址重命名为street。无论如何,而不是覆盖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());
}