返回多个字符串格式

时间:2015-10-17 15:14:43

标签: java

我是这个论坛的新手。我被困在代码的一部分上。 我的代码的一种方法给了我这个信息:

getFullAddress()应该将地址作为格式化的String返回,每行一个项目: e.g:

23 High Street
Newcastle
NE1 1NE 

问题是我被卡住了,我尝试了一切,但没有任何作用。

这是我的代码:

/**
* Write a description of class Address here.
* 
* @author Bento Xavier
* @version 10/17/2015
*/
public class Address
{
  private String postcode;
  private String street;
  private String town;

 public Address(String street, String town, String postcode)
 {
   this.street = street;
   this.town = town;
   this.postcode = postcode;
 }

 public String getFullAddress()
 {
    String fullAddress = "";
    fullAddress = ;
 }

 public String getPostcode()
 {
   return postcode;
 }

public String getStreet()
{
   return street;
}

 public String getTown()
 {
   return town;
 }

 public void printAddress()
 {
   System.out.println(street + " \n" + town + " \n" + postcode );
 }

 public void setFullAddress(String street, String town, String postcode)
 {
   this.street = street;
   this.town = town;
   this.postcode = postcode;
 }

 public void setPostcode(String postcode)
 {
   this.postcode = postcode;
 }

 public void setStreet(String street)
 {
   this.street = street;
 }

 public void setTown(String town)
 {
   this.town = town;
 }
}

提前感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您没有在getFullAddress()中返回任何内容。将getFullAddress方法更改为:

public String getFullAddress() {
    final String separator = System.getProperty("line.separator"); //final indicates the variable will not change
    return getStreet() + separator  + getTown() + separator  + getPostcode();
}

我建议您使用System.getProperty("line.separator");而不是\n,因为\n无法在每个操作系统上正常运行。使用System.getProperty()获取行分隔符将为每个操作系统返回正确的换行符。

答案 1 :(得分:0)

只需将字符串连接在它们之间的换行符:

public String getFullAddress() {
    return String.format("%s%n%s%n", getStreet(), getTown(), getPostcode());
}