/** * This class stores animal names (e.g. Spot)and their types (e.g. dog). */ import java.util.ArrayList; public class TheDataBase { /** The list of animals and types */ ArrayList animals = new ArrayList(); ArrayList types = new ArrayList(); /** Constructor: * Create a new TheDataBase object */ public TheDataBase() { } /** Add a new animal if the animal is not already in the list. * @return the animal in the list, if already in the list, otherwise, return the new animal. */ public Animal addAnimal(Animal an) { for (Animal a: animals) { if (a.getName().equals(an.getName())) { return a; // animal is already in the list } } animals.add(an); return an; } /** If type is not in the list, add it ; * @return the type in the list, if already in the list, otherwise, return the new type. */ public Type addType(Type t) { for (Type tName: types) { if (tName.getName().equals(t.getName())) { return tName; // animal is already in the list } } types.add(t); return t; } /** If aName is in the list, it removes it and returns true. * Otherwise, it returns false. */ public boolean removeAnimal(String aName) { for (int i = 0; i < animals.size(); i++) { Animal animal = animals.get(i); if (aName.equals(animal.getName())) { animals.remove(i); return true; } } return false; } /* Accessor: * @param i the index of the object being accessed. * @return the ith Type object */ public Type getType(int i) { return types.get(i); } /* Accessor: * @param i the index of the object being accessed. * @return the ith Animal object */ public Animal getAnimal(int i) { return animals.get(i); } /** Remove the name at index iName from the list and return true, assuming the index is in * the proper range. Otherwise, return false. */ public boolean removeAnimal(int iName) { if (iName < animals.size()) { animals.remove(iName); return true; } return false; } /* @return a String representation of the list of all the animal names. */ public String printAnimalNames() { String s = ""; for (int i = 0; i < animals.size(); i++) { s += i+". " + animals.get(i).getName() + "\n"; } return s; } /* @return a String representation of the list of all the type names. */ public String printTypeNames() { String s = ""; for (int i = 0; i < types.size(); i++) { s += i+". " + types.get(i).getName() + "\n"; } return s; } /** Create a String representation of everything in the database. */ public String toString() { String s = "The animals are: "; for (Animal a: animals) { s += "\n " + a.getName() + " with type: " + a.getTypeName(); } s += "\nThe types are: "; for (Type t: types) { s += "\n " + t; } return s; } }