java - 在基于文本的“地牢爬行”中获取输出时,如何在 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
解决方案
您始终可以使用@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 导入您的类,您也可以改用纯字符串连接
推荐阅读
- php - 数据属性只返回第一个值
- python - 为什么这不会陷入无限循环?
- python-3.x - 无法更改我的班级的实例属性?
- python - 在保持索引顺序的同时连接两个 Pandas DataFrame
- node.js - AWS EC2 实例上的 socket.io
- swift - 为什么函数 setValues 不会更改 Phone 类型的 NSManaged 对象的值?
- bash - 如何修复错误 agrep:模式太长(具有 > 32 个字符)如果字符串中没有句号,它不会显示错误?
- git - 如何维护存储库的多个分支?
- apache - 将子域重定向到特定目录
- flutter - Flutter 支持哪些字体无需外部导入?