为什么我打电话给System.out.println(classroom.toStringLong())
时我得到:教室:一个空的大型演讲厅,空为零?
正确的输出应该是:教室:一个大型的演讲厅,门外面是人行道
public class Main {
public static void main(String[] args) {
Space classroom = new Space();
classroom.setName("classroom");
classroom.setDescription("a large lecture hall");
Space sidewalk = new Space();
sidewalk.setName("sidewalk");
sidewalk.setDescription("a plain concrete sidewalk with weeds growing through the cracks");
Portal door = new Portal();
door.setName("door");
door.setDirection("outside");
door.setDestination(sidewalk);
classroom.setPortal(door);
System.out.println(classroom.toStringLong());
}
}
public class Space {
private String _name;
private String _description;
private Portal _portal;
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String getName() {
return _name;
}
public void setName(String _name){
this._name=_name;
}
public String getDescription() {
return _description;
}
public void setDescription(String _description){
this._description=_description;
}
public Portal getPortal() {
return _portal;
}
public void setPortal(Portal _portal){
this._portal=_portal;
}
public String toString(){
return _name;
}
public String toStringLong(){
if (_portal!= null){
Portal p= new Portal();
p.toStringLong();
String Longcombined=_name + ": " + _description+" with a "+p.toStringLong();
return Longcombined;
}
else{
String Long=_name + ": " + _description;
return Long;
}
}
}
public class Portal {
private String _name;
private String _direction;
private Space _destination;
public String getName() {
return _name;
}
public void setName(String _name){
this._name=_name;
}
public String getDirection(){
return _direction;
}
public void setDirection(String _direction){
this._direction=_direction;
}
public Space getDestination(){
return _destination;
}
public void setDestination(Space _destination){
this._destination=_destination;
}
public String toString(){
String combined=_name+ " that goes "+_direction;
return combined;
}
public String toStringLong(){
Space space=new Space();
String combined=toString() + " to " + space.getDescription() ;
return combined;
}
}
答案 0 :(得分:3)
您正在创建一个新的空间对象并打印其描述为null 将toStringLong()方法重写为
In class Space
public String toStringLong(){
if (_portal!= null)
{
// comment this Portal p= new Portal();
_portal.toStringLong();
String Longcombined=_name + ": " + _description+" with a "+_portal.toStringLong();
return Longcombined;
}
else
{
String Long=_name + ": " + _description;
return Long;
}
}
Class Portal ->
public String toStringLong()
{
String combined=toString() + " to " + _destination.getDescription() ;
return combined;
}
希望这能解决您的问题。
答案 1 :(得分:0)
运行此代码"空格=新空格();"在toStringLogn()方法内部,创建了新的空间对象,并且还使用其默认值初始化了此对象的所有即时变量。 String的默认值是" null"。这就是使用此对象时获得null值的原因。
最好按照以下方式重新定义toStringLong(),
String combined = toString()+"到" + _destination.getDescription();
返回合并;