2014-10-11 119 views
0

我的toString方法未提供所需的結果。toString()方法打印空值

我想是這樣的: [潛艇,5,假]

我得到的是: [NULL,0,假]

我的類看起來像這樣

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; 

} 
} 

我搜索了類似的東西,而其他人的問題是他們沒有使用這個關鍵字。由於我使用它,我看不到我做錯了什麼。

+2

作業是從右到左。 – 2014-10-11 15:00:45

+0

@ user2740689提示:您的'toString()'的實現可以簡化爲單行'return「[」+ name +「,」+ size +「,」+ isDestroyed +「]」; – 2014-10-11 15:15:17

回答

2
n = this.name; 

應該

this.name = n; 

同爲其他字段變量

+0

謝謝很多,它的工作!但爲什麼? – Rasmus 2014-10-11 15:02:33

+0

將實例變量(分別默認爲「null」,「0」和「false」)分配給局部變量而不是其他方式。閱讀:[作業](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html) – Reimeus 2014-10-11 15:30:20

0

你在錯誤的方式分配值。

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

或名稱。

this.name="XYZ"; 

你不能valriable存入值

"YYZ"=thi.name; 
0
n = this.name; 

手段分配的 「this.name」 到 「n」 的值。但是「this.name」的值爲空,所以你什麼也得不到。