/** * This program stores animal names. */ import java.util.ArrayList; public class TheDataBase { /** The ascii file where the names are stored. */ private String filename = "animals.txt"; /** The list of animal names */ private static ArrayList animals = new ArrayList(); /** Create a new TheDataBase object */ public TheDataBase() { animals = FileIO.readFile(filename); } /** If animal is not in the list, add it and return true; * Otherwise, just return false. */ public boolean addAnimal(String a) { for (Animal aName: animals) { if (aName.equals(a)) { return false; // animal is already in the list } } animals.add(new Animal(a)); return true; } /** If aName is in the list, it removes it and returns true. * Otherwise, it returns false. */ public boolean removeAnimal(String aName) { // for Strings, one camoveAnumn just call animals.remove(a); // However, for general objects, one needs to loop, e.t. : 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; } /** 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; } /** Creates a String representation of the animals */ public String toString() { return animals.toString(); } // used only for testing public static void main(String[] args) { TheDataBase db = new TheDataBase(); db.addAnimal("Zebra"); db.addAnimal("Deer"); db.addAnimal("Cat"); db.addAnimal("Deer"); System.out.println("The animals are " + db); System.out.println("removing Cat "); db.removeAnimal("Cat"); System.out.println("The animals now are " + db); System.out.println("removing Mouse "); if (db.removeAnimal("Mouse")) System.out.println("The animals now are " + db); else System.out.println("Mouse is not in the list"); } }