【发布时间】:2014-10-11 14:59:49
【问题描述】:
我的 toString 方法没有给出想要的结果。
我想要的是这样的: [潜艇,5,假]
我得到的是: [null, 0, false]
我的班级是这样的
public class Ship {
private String name;
private int size;
private boolean isDestroyed;
public Ship(String n, int s, boolean d) {
n = this.name;
s = this.size;
d = this.isDestroyed;
}
public String toString() {
String output = "";
output = "[" + name + ", " + size + ", " + isDestroyed + "]";
return output;
}
}
我搜索过类似的东西,其他人的问题是他们没有使用 this 关键字。自从我使用它,我看不出我做错了什么。
【问题讨论】:
-
分配从右到左。
-
@user2740689 提示:您的
toString()的实现可以简化为单行return "[" + name + ", " + size + ", " + isDestroyed + "]";