作为我项目的一部分,我必须创建一个循环来重复向队列中添加对象
这是代码
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在上面执行时,它会给我
[queuepart.Rabbits@7852e922]
而不是兔子。
使用上面的代码,我尝试使用以下行从我的Rabbits类调用getName()方法
System.out.println(queuepart.Rabbits@7852e922.getName());
但它错误地给出了。据我所知,这是因为该对象尚未初始化。
这是我的兔子班
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;
}
}
我想我仍然可以使用错误提供的名称继续我项目的下一步,但是我的项目结论要求我拥有正确的兔子名称,例如Rabbit 1,Rabbit 2等等
谢谢你,很抱歉这篇长篇文章。 :)
答案 0 :(得分:1)
答案 1 :(得分:0)
覆盖toString()
类的Object
方法。在你Rabbits
上添加
@Override
public String toString(){
return "[Rabbit name: " + this.name + " - Rabbit speed: " + this.speed + " ]";
}
答案 2 :(得分:0)
更改您的Rabbit类,以便覆盖Object类中的toString()方法,如下所示:
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;
}
}