gpt4 book ai didi

java - 与面向对象方法的斗争

转载 作者:行者123 更新时间:2023-11-30 01:48:09 24 4
gpt4 key购买 nike

我无法弄清楚 getExits() 需要什么才能获得问题所请求的输出。

//构造函数

public class Room {

private String name;
private String description;
private Room north;
private Room east;
private Room south;
private Room west;

public Room (String name, String description){
this.name = name;
this.description = description;
}

public Room getEast(){
return this.east;
}

public String getExits (){
//
}

public String getName(){
return this.name;
}

public Room getNorth(){
return this.north;
}

public Room getWest(){
return this.west;
}

public Room getSouth(){
return this.south;
}

public void setExits (Room n, Room e, Room w, Room s){
this.north = n;
this.east = e;
this.west = w;
this.south = s;
}

public String toString(){
return String.format("%s\n%s\n%s", this.name, this.description,getExits());
}
}

//主要方法

public class Tester{

public static void main(String []args){

Room hall = new Room ("Hall", "It's Dark");
Room bed = new Room ("Bed", "Tiny Room");
Room bath = new Room ("Bath", "Toilets here");
Room dine = new Room ("Dine", "Table and chairs");
hall.setExits(bed, bath, dine, null);

System.out.println(hall);

}
}

预期输出:

Hall
It's Dark
North: Dine
East: Bath
West: Dining

最佳答案

获得您想要的内容的“面向对象”方法是重写 Room 类中的 toString() 方法,以便它返回名称房间的

然后修改 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;
}
}

关于java - 与面向对象方法的斗争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57158229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com