Spaces:
Running
Running
| In the attached program, the class Dog is defined. | |
| See the definition of the class, and then write the test class method | |
| public static String oldestDog(ArrayList<Dog> dogs) | |
| which takes as its parameter a list of dogs. The method searches for the oldest dog's name and returns it. | |
| import java.util.ArrayList; | |
| import java.util.Arrays; | |
| import java.util.Collections; | |
| import java.util.Random; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| String[] nt = {"Fifi","Jackie","Lassie","Rin-Tin-Tin","Snoopy","Scooby-Doo"}; | |
| for (int testi = 1; testi <= 3; testi++) { | |
| System.out.println("Test " + testi); | |
| ArrayList<String> names = new ArrayList<String>(Arrays.asList(nt)); | |
| int year = r.nextInt(100) + 1900; | |
| ArrayList<Dog> dogs = new ArrayList<>(); | |
| while (!names.isEmpty()) { | |
| Dog k = new Dog(names.remove(r.nextInt(names.size())), year); | |
| year += r.nextInt(15) + 1; | |
| dogs.add(k); | |
| } | |
| Collections.shuffle(dogs); | |
| System.out.println("Dogs: " + dogs); | |
| System.out.println("Oldest dog: " + oldestDog(dogs)); | |
| System.out.println("List after method call: " + dogs); | |
| System.out.println(""); | |
| } | |
| } | |
| //ADD HERE | |
| public static String oldestDog(ArrayList<Dog> dogs) { | |
| int oldestDogYear = 9999; | |
| String oldestDogName = ""; | |
| for (Dog dog: dogs) { | |
| // we want the smallest dog year (for the oldest dog) | |
| if (dog.getBirthyear() < oldestDogYear) { | |
| oldestDogYear = dog.getBirthyear(); | |
| oldestDogName = dog.getName(); | |
| } | |
| } | |
| return oldestDogName; | |
| } | |
| } | |
| class Dog { | |
| private String name; | |
| private int birthyear; | |
| public Dog(String name, int birthyear) { | |
| this.name = name; | |
| this.birthyear = birthyear; | |
| } | |
| public String getName() { | |
| return name; | |
| } | |
| public int getBirthyear() { | |
| return birthyear; | |
| } | |
| @Override | |
| public String toString() { | |
| return name + " (" + birthyear + ")"; | |
| } | |
| } | |
| Test 1 | |
| Dogs: [Lassie (2018), Snoopy (1995), Fifi (1993), Scooby-Doo (2013), Rin-Tin-Tin (2000), Jackie (2012)] | |
| Oldest dog: Fifi | |
| List after method call: [Lassie (2018), Snoopy (1995), Fifi (1993), Scooby-Doo (2013), Rin-Tin-Tin (2000), Jackie (2012)] | |
| Test 2 | |
| Dogs: [Scooby-Doo (1931), Lassie (1937), Jackie (1961), Snoopy (1948), Fifi (1964), Rin-Tin-Tin (1976)] | |
| Oldest dog: Scooby-Doo | |
| List after method call: [Scooby-Doo (1931), Lassie (1937), Jackie (1961), Snoopy (1948), Fifi (1964), Rin-Tin-Tin (1976)] | |
| Test 3 | |
| Dogs: [Scooby-Doo (1937), Fifi (1947), Snoopy (1931), Jackie (1921), Lassie (1962), Rin-Tin-Tin (1946)] | |
| Oldest dog: Jackie | |
| List after method call: [Scooby-Doo (1937), Fifi (1947), Snoopy (1931), Jackie (1921), Lassie (1962), Rin-Tin-Tin (1946)] | |