2016-04-05 52 views
1

由於我的項目的一部分,我不得不做出一個循環反覆對象添加到我的隊列出現哈希碼而不是int,對象名稱顯示不正確?

下面是代碼

for(int rabbitcounter=0; rabbitcounter<30;rabbitcounter++) { 
    yettoracequeue.add(new Rabbits("Rabbit" + rabbitcounter, Math.random()*100)); 
    System.out.println(yettoracequeue); 
    System.out.println(rabbitcounter); 

我一直使用的System.out.println檢查,如果一切進展如預期。

然而,當上面的System.out.println執行,它給了我

[[email protected]] 

相反兔1

使用上面的,我想從我的兔調用getName()方法上面用下面的線

System.out.println([email protected]()); 

但它給出了錯誤。從我的理解是因爲對象尚未初始化。

這裏是我的兔類

package queuepart; 
public class Rabbits { 
// properties of rabbits 
private double speed; 
private String name; 
//private int counter = 1; 
//Constructor, must be name of object 
public Rabbits() { 

} 

public Rabbits(String name, double speed) { 
    this.name = name; 
    this.speed = speed; 
    //counter++; 
} 
//Speedgetter 
public double getSpeed() { 
    return speed; 
} 

//Namegetter 
public String getName() { 
    return name; 
} 

//Speedsetter 
public void setSpeed (double speed) { 
    this.speed = speed; 
} 

//Namesetter 
public void setName(String name) { 
    this.name = name; 
} 

}

我覺得我還是能夠繼續我與錯誤提供名稱項目的下一個步驟,但我的項目的結論需要我有正確的兔子名稱,例如兔子1,兔子2等等

謝謝你,對不起,很長的職位。 :)

+1

什麼是'yettoracequeue'? – Hackerdarshi

+3

覆蓋'Rabbit'類中的'toString'方法,這是您在執行'System.out.println(someRabbit)'時調用的方法。 – Berger

+0

@Hackerdarshi這是一個隊列,我將我的兔子對象添加到。 – AdventL

回答

1

您應該重寫toString()方法在Rabbits

@Override 
public String toString() { 
    return name; 
} 
0

覆蓋Object類的toString()方法。在你Rabbits類添加

@Override 
public String toString(){ 
    return "[Rabbit name: " + this.name + " - Rabbit speed: " + this.speed + " ]"; 
} 
0

更改您的兔類,以重寫ToString()從如下對象類methos:

package queuepart; 
public class Rabbits { 
    // properties of rabbits 
    private double speed; 
    private String name; 
    //private int counter = 1; 
    //Constructor, must be name of object 
    public Rabbits() { 

    } 

    public Rabbits(String name, double speed) { 
     this.name = name; 
     this.speed = speed; 
     //counter++; 
    } 
    //Speedgetter 
    public double getSpeed() { 
     return speed; 
    } 

    //Namegetter 
    public String getName() { 
     return name; 
    } 

    //Speedsetter 
    public void setSpeed (double speed) { 
     this.speed = speed; 
    } 

    //Namesetter 
    public void setName(String name) { 
     this.name = name; 
    } 

    public String toString(){ 
     return this.name + " " + this.speed; 
    } 
}