Method that returns string containing multiple variables

Go To StackoverFlow.com

0

Here is a constructor I wrote that holds address information, but I'm having trouble with the final part, where I have to return a string that holds name, address, city, state zipcode. What would be the correct way to write it?

public class Address {

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;



}

}

2012-04-04 21:48
by Evolutionary High
Do you need it in one whole string? Or could it be an array of strings? Also why are you calling getaddress() inside getaddress()??? - dann.dev 2012-04-04 21:51


3

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

A few notes:

  • only one return, followed by the object to return, which is a result of string concatenation
  • call your concatenating method getFullAddress() to distinguish it from the getter.
  • use lower-case variable names
  • getters and setters should get camel-case: setCity(), getState()
2012-04-04 21:50
by Bozho
I would also like to point out that you can override your address object's toStrin - Kevin 2012-04-04 21:55
yes, but since .toString() should be used mainly for debugging, if he needs this for other purposes, he'd better make a new metho - Bozho 2012-04-04 22:32


0

I think your problem is probably that you are calling getaddress() inside of getaddress() rather than using address

EDIT: and as Bozho pointed out, only one return per statement in a method.

2012-04-04 21:51
by dann.dev


0

I would rename the variable address to street for clarity. No matter though, rather than overridding toString() I would add getters on each of the fields and add a static utility class to print the address with the following method

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-04 22:04
by TechTrip
Obviously this is a simple formatter but it should get you on the path - TechTrip 2012-04-04 22:05
Ads