Reputation: 1307
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;
}
}
Upvotes: 0
Views: 4957
Reputation: 4537
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());
}
Upvotes: 1
Reputation: 2494
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.
Upvotes: 0
Reputation: 597234
return address + " " + state + " " + city + " " + code;
A few notes:
return
, followed by the object to return, which is a result of string concatenationgetFullAddress()
to distinguish it from the getter.setCity()
, getState()
Upvotes: 3