简体   繁体   中英

How do I return null in a getter method and not print "null" in the toString method when getting output in a text based "dungeon crawl"?

I am trying to create a Room object that uses getter and setter methods. For each Room, there is either a Room or no Room (null) to the N, E, W or S.

1) Each Room object contains references to up to four other Room objects (N, E, W, or S)

2) toString() method should include the room's name, room's description, and the method 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;
 }

} // end class DungeonCrawl

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

I don't know if I understood your question, but maybe you can do something like this:

public String toString() {
    return yourVariable == null ? "" : "text"
}

In this case if yourVar is null, it will be returned in the getter method while the toString will return whatever you want.

You can always use @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();
    }

This does require importing StringBuilder to your class, you could also use plain string concatenation instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM