Spaces:
Running
Running
File size: 3,053 Bytes
9bf9ebe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | 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)]
|