返回包含多个变量的字符串的方法

时间:2012-04-04 21:48:20

标签: java string

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

公共类地址{

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;



}

}

3 个答案:

答案 0 :(得分:3)

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

一些注意事项:

  • 只有一个return,后跟要返回的对象,这是字符串连接的结果
  • 调用您的连接方法getFullAddress(),以区别于getter。
  • 使用小写变量名称
  • getter和setter应该是camel-case: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());
}