-6

So, i have ArrayList which i store animals in.

private ArrayList<Animal> catalog = new ArrayList<>();

Now, i need to print the catalog into my output when i press 4 into my output.

case 4:
                System.out.println("List of animals: ");
                printIt();   //Function to print catalog
                break;

I tried to do it with

    private boolean InList(String name) {
    for (int i = 0; i < catalog.size(); i++) {
        if (name.equalsIgnoreCase(catalog.get(i).getName())) {
            return true;
        }
    }
    return false;
}

But it's not working. Can you guys help me to get this piece of code?

3 Answers3

0

Do something like this if you want it to return a String.

String printIt(ArrayList<Animal> animals) {
String temp = "";
for(Animal animal : animals) {
temp += animal.getName() + "\n";
}
return temp;
}

Although I don't see a need for that, just print it right away.

void printIt(ArrayList<Animal> animals) {
for(Animal animal : animals) {
System.out.println(animal.getName());
}
}
Austin
  • 4,801
  • 6
  • 34
  • 54
0

Defining a method that prints is maybe too much, you can just do

System.out.println("List of animals: "+ catalog );

but for that you must override the toString method in the class animal...

if you dont override that you will get something printed like

[animalcatalogjava.Animal@33909752]

that is the defaukt to string of the object...

something like in the format:

package.class@hashcode..

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

you need to override toString() method for printing user friendly names of the objects and it helps in debugging.

equals() method for comparing two animal objects are same or not.

For more information on how or when to override Object class methods https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html