【问题标题】:toString() method prints nullstoString() 方法打印空值
【发布时间】: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 + "]";

标签: java tostring


【解决方案1】:
n = this.name;

应该是

this.name = n;

其他字段变量相同

【讨论】:

  • 您将实例变量(默认分别为null0false)分配给局部变量,而不是相反。阅读:Assignment
【解决方案2】:

你以错误的方式分配价值。

this.name= n;
this.size= s;
this.isDestroyed= d;

或者是名字。

this.name="XYZ";

你不能将变量存储到值中

"YYZ"=thi.name;

【讨论】:

    【解决方案3】:
    n = this.name;
    

    表示将“this.name”的值分配给“n”。但是“this.name”的值是空的,所以你什么也得不到。

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 1970-01-01
      • 2014-06-02
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      相关资源
      最近更新 更多