3 回答

TA貢獻1851條經驗 獲得超4個贊
獲得所需內容的“面向對象”方法是覆蓋類toString()中的方法Room,以便它返回房間的名稱。
然后修改getExits(),如下所示:
public String getExits (){
StringBuilder sb = new StringBuilder();
if(this.north != null) sb.append(this.north.toString()).append(" North") else sb.append("No Exit for: North");
...
return sb.toString();
}
....
public class Room {
private String name;
...
@Override
public String toString() {
return this.name;
}
}

TA貢獻1871條經驗 獲得超8個贊
exit不是您可以用String. 在 OO 世界中,它應該是對更有意義的對象的引用。我會和
public Collection<Room> getExits();
或者
public Map<String, Room> getExits();
它準確地描述了您可以從大廳到達哪里。在這里,我們假設“出口”是通往另一個房間的門口。
你可以回來
Arrays.asList(northRoom, eastRoom, southRoom, westRoom);
或者
Map<String, Room> map = new HashMap<>();
map.put("north", northRoom);
...
return map;
然后您將能夠提供String返回集合中的任何表示。
它就像一個放置在大廳里的標志,可以幫助人們導航。盡管它可以用另一個標志(更詳細/準確的標志)代替,但建筑物的結構是不變的,您不會改變它。您只是以不同的方式表示它。
String simpleSign = "You can go to: " + getExits().stream().map(Object::toString).collect(Collectors.join(", "));
或者
String detailedSign = "Directions to go: " + getExits().entrySet().stream().map(e -> e.getKey() + " -> " + e.getValue().toString()).collect(Collectors.join("\n"));

TA貢獻1877條經驗 獲得超1個贊
這是一種做事的方法。這有點尷尬,因為您必須為每種情況檢查 null - 如果不是這種情況,您可以刪除這些檢查。
public String getExits (){
List<String> exits = new ArrayList<>();
if (north != null) exits.add("North: " + north.name);
if (south != null) exits.add("South: " + south.name);
if (east != null) exits.add("East: " + east.name);
if (west != null) exits.add("West: " + west.name);
return String.join("\n", exits);
}
添加回答
舉報