/* * CS161 Section 001 * Shows an ArrayList of Pet * */ import java.util.ArrayList; public class Clinic { private ArrayList ourPets; // the Pets are stored in this ArrayList. public Clinic() { ourPets = new ArrayList(); } public void addPet(Pet p) { ourPets.add(p); } public int countPets() { return ourPets.size(); } public ArrayList getPets() { return ourPets; } public double getAverageWeight() { double total = 0; // keeps the running sum of weights for(int i=0; i<=ourPets.size(); i++) { total = total + ourPets.get(i).getWeight(); } /* * Alternative way to traverse the list of Pets. for(Pet p : ourPets) { total = total + p.getWeight(); } */ int number = countPets(); if(number == 0) { return 0; } else { return total/number; } } public static void main(String[] args) { Clinic c = new Clinic(); int numPets = c.countPets(); Pet p1 = new Pet(); p1.setName("Nemo"); p1.setWeight(13.5); c.addPet(p1); System.out.println(c.countPets()); Pet p2 = new Pet("Loki"); p2.setWeight(12.7); c.addPet(p2); System.out.println(c.countPets()); System.out.println(c); // What does this print? No toString() defined for Clinic. System.out.println(c.getPets()); // What does this print? toString defined for ArrayList and Pet. System.out.println(c.getAverageWeight()); } }