0

I'm creating an array of objects and having an issue in printing this easily

Dog Dogobj[]=new Dog[2]; // Dog objects within this array
Dogobj[0] = new Dog(Age, weight, name); 
Dogobj[1] = new Dog(Age, weight, name);

System.out.println("Dog age?: "+Dogobj[0].Dogtype etc.) 

Now after creating these I can't find an easy way of printing these that isn't a lot of long lines. This is the only way I have found I can do it (above)- there are about 10 variables for each object so they are very long lines.

1
  • 1
    Have you added a toString() method to your Dog class? Commented Jan 19, 2021 at 13:09

3 Answers 3

2

You may do something like:

for (Dog dog : Dogobj) {
    System.out.println(dog); // This way every dog will be printed in a new line
}

And of course, implement Dog's toString method.

in "Dog" class definition:

@Overrride
public String toString() {
    "Age: " + age + "," +
    "weight: " + weight + ","
    "name: " + name;
}

if you want every dog's member will be printed in a new line, you may implement toString that way:

@Overrride
public String toString() {
    "Age: " + age + ",\n" +
    "weight: " + weight + ",\n"
    "name: " + name;
}
Sign up to request clarification or add additional context in comments.

Comments

1
  1. Implement toString() method in your DogObj class. Inside this method you can return a string that needs to be printed from the object.

  2. Print the objects inside a for loop.

    for (int i = 0; i < Dogobj.length; i++) {
               System.out.println(DogObj[i]);
           }

Comments

1

Use this:

  `for(String d : dog)`
  1. List item:

    {System.out.println(d);}

  2. Or this:

for(int i=0 ; i<dog.length ; i++){ System.out.println(dog[i]);}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.