我有一个包含这些字段的州级
String name;
City capital;
ArrayList<String> neighbors;
我有一个toString()方法
public String toString(){
return ("new State(" +
this.name + ", " +
this.capital + ", " +
this.neighbors + ")\n");
}
我正试图在状态
上测试这个方法State ME = new State("ME", augusta, MEneighbors );
其中augusta是已定义的城市,而MEneighbors是带有
的ArrayListMEneighbors.add("NH");
这是我到目前为止的测试
t.checkExpect(ME.toString(),
"new State(ME, " + augusta.toString() + ", " + [NH] + ")");
我不太明白为什么这不起作用。它一直工作到ArrayList MEneighbors。如何将ArrayList添加为String?
非常感谢。
答案 0 :(得分:2)
即使您将代码修改为:
t.checkExpect(ME.toString(),
"new State(ME, " + augusta.toString() + ", " + "[NH]" + ")");
注意:括号内的引号。
你仍然忘记添加&#34; \ n&#34;在右边!因为你的toString方法添加&#34; \ n&#34;最后!
答案 1 :(得分:0)
定义toString方法时,为ArrayList调用toString方法,就像这样
public String toString(){
return ("new State(" +
this.name + ", " +
this.capital + ", " +
this.neighbors.toString() + ")\n");
}
toString
方法
Returns a string representation of this collection. The string representation consists of
a list of the collection's elements in the order they are returned by its iterator,
enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", "
(comma and space). Elements are converted to strings as by String.valueOf(Object).