1

As part of my project, I have to make a loop to repeatedly add objects to my queue

Here is the code

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

I always use System.out.println to check if things are going as expected.

However when the System.out.println executes above, it gives me

[queuepart.Rabbits@7852e922]

Instead of Rabbit 1.

Using the above, I tried to call the getName() method from my Rabbits class on it with the following line

System.out.println(queuepart.Rabbits@7852e922.getName());

but it gives at error. From what I understand it is because the object has not been initialized.

Here is my Rabbits class

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;
}

}

I think I am still able to proceed to the next step of my project with the wrongly provided names but the conclusion of my project requires me to have the correct rabbit names e.g Rabbit 1, Rabbit 2 etc etc

Thank you and sorry for the long post. :)

AdventL
  • 47
  • 1
  • 1
  • 8

3 Answers3

1

You should override toString() method in your Rabbits class

@Override
public String toString() {
    return name;
}
bedrin
  • 4,458
  • 32
  • 53
0

Override the toString() method of Object class. On you Rabbits class add

@Override
public String toString(){
   return "[Rabbit name: " + this.name + " - Rabbit speed: " + this.speed + " ]";
}
A0__oN
  • 8,740
  • 6
  • 40
  • 61
0

Change your Rabbit class so as to override the toString() methos from Object class as below:

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;
    } 
}
KayV
  • 12,987
  • 11
  • 98
  • 148