import java.util.*; import java.io.*; /** * class Zoo simulates storing animals in a collection. * * @author D Newton * */ public class Zoo { private ArrayList animalCollection; private int lionCount; private int tigerCount; private int elephantCount; private int otherCount; /** * Create an "empty" zoo */ public Zoo() { animalCollection = new ArrayList(); lionCount = 0; tigerCount = 0; elephantCount = 0; otherCount = 0; } /** * Create a zoo and populate it using data from a text file */ public Zoo(String fileName) throws FileNotFoundException { this(); readAnimalData(fileName); } /** * Adds an animal to the zoo * * @param animal an Animal object, the animal to be added */ public void storeAnimal(Animal animal) { animalCollection.add(animal); } /** * Shows an animal by printing it's details. This includes * it's position in the collection. * * @param listPosition the position of the animal */ public void showAnimal(int listPosition) { Animal animal; if( listPosition < animalCollection.size() ) { animal = animalCollection.get(listPosition); System.out.println("Position " + listPosition + ": " + animal); } } /** * Returns how many animals are stored in the collection * * @return the number of animals in the collection */ public int numberOfAnimals() { return animalCollection.size(); } /** * Displays all the animals in the collection * */ public void showAllAnimals() { System.out.println("Zoo"); System.out.println("==="); int listPosition = 0; while( listPositionlistPosition the position of the animal */ public void removeAnimal(int listPosition) { if( listPosition>=0 && listPosition it = animalCollection.iterator(); while( it.hasNext() ) { Animal currentAnimal = it.next(); String species = currentAnimal.getSpecies(); if( species.equalsIgnoreCase("lion") ) lionCount++; else if( species.equalsIgnoreCase("tiger") ) tigerCount++; else if( species.equalsIgnoreCase("elephant") ) elephantCount++; else otherCount++; } } /** * Writes animal data to a file * * @param fileName a String, the name of the * text file in which the data will be stored. * * @throws FileNotFoundException */ public void writeAnimalData(String fileName) throws FileNotFoundException { PrintWriter pWriter = new PrintWriter(fileName); for(Animal a: animalCollection) { String lineOfOutput = a.getName() + "," + a.getSpecies(); pWriter.println(lineOfOutput); } pWriter.close(); } /** * Reads animal data from a file and adds corresponding animals to the zoo * * @param fileName a String, the name of the * text file in which the data is stored. * * @throws FileNotFoundException */ public void readAnimalData(String fileName) throws FileNotFoundException { File dataFile = new File(fileName); Scanner scanner = new Scanner(dataFile); scanner.useDelimiter("[,\n]"); while( scanner.hasNext() ) { String name = scanner.next(); name.trim(); String species = scanner.next(); species.trim(); storeAnimal( new Animal(species, name) ); } scanner.close(); } }