首页 > 解决方案 > 在基于文本的“地牢爬行”中获取输出时,如何在 getter 方法中返回 null 而不在 toString 方法中打印“null”?

问题描述

我正在尝试创建一个使用 getter 和 setter 方法的 Room 对象。对于每个 Room,N、E、W 或 S 有一个 Room 或没有 Room(空)。

1) 每个 Room 对象包含对最多四个其他 Room 对象(N、E、W 或 S)的引用

2) toString() 方法应该包括房间的名称、房间的描述和方法 getExits()

public class Room {

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

 public Room(String name, String description) {
      this.name = name;
      this.description = description;
 } //end Room constructor class


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

 // public String getExits() {
 //      if()
 // }

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

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

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

 public Room getSouth() {
      if (this.south == null) {
           return null;
      }
      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;
 } //end setExits

 public String toString() {
      String nm;
      nm = "["+name+"]"+"\n" +
      description + "\n" +
      getExits(); //need this method 
      return nm;
 }

} // 结束类 DungeonCrawl

#this is what I wan't my output to look like#
[Hall]
Its Dark.
[N]orth: Bed
[E]ast : Bath
[W]est : Dining

标签: javamethods

解决方案


您始终可以使用@override。

    @Override
    public String toString(){
    return "["+name+"]\n"+description+"\n"+getExits();
    }

    public String getExits(){
    StringBuilder builder = new StringBuilder();
    if(west != null)
    builder.append("[W]est: "+west.getName()+"\n");
    else
    builder.append(";"); //append nothing if exit does not exist in that direction
    //repeat for every room
    return builder.toString();
    }

这确实需要将 StringBuilder 导入您的类,您也可以改用纯字符串连接


推荐阅读