7.9. Additional Practice¶
Question 1
Refer to the UML diagram below. Write a static method named
listCarnivores that takes an array of Animal objects and
returns an String[] containing the names of all animals whose diet
is “Carnivore”.
Method header to complete:
/**
* Returns an array of the names of all carnivorous animals
* in the given array.
*
* @param animals an array of Animal objects
* @return a {@code String[]} containing the names of the carnivores
*/
public static String[] listCarnivores(Animal[] animals) {
// your code here
} // listCarnivores
Solution
1/**
2 * Returns an array of the names of all carnivorous animals
3 * in the given array. Null arrays and null entries are ignored.
4 *
5 * @param animals an array of {@code Animal} objects
6 * @return a {@code String[]} containing the names of the carnivores
7 */
8public static String[] listCarnivores(Animal[] animals) {
9
10 if (animals == null) {
11 return new String[0];
12 }
13
14 // First, count the number of carnivores
15 int count = 0;
16 for (Animal individual : animals) {
17 if (individual != null && individual.getDiet().equals("Carnivore")) {
18 count++;
19 } // if
20 } // for
21
22 // Create array of correct size
23 String[] carnivores = new String[count];
24
25 // Fill the array
26 int index = 0;
27 for (Animal individual : animals) {
28 if (individual != null && "Carnivore".equals(individual.getDiet())) {
29 carnivores[index] = individual.getName();
30 index++;
31 } // if
32 } // for
33
34 return carnivores;
35} // listCarnivores
Question 2
Refer to the UML diagram below. Write a static method named
countByGenus that takes an array of Animal objects and a
String representing a genus, and returns the number of animals
in the array that belong to that genus.
Method header to complete:
/**
* Counts the number of animals in the given array that belong
* to the specified genus. Null arrays, null genus, or null
* entries in the array are ignored.
*
* @param animals an array of {@code Animal} objects
* @param genus the genus to count
* @return the number of animals matching the specified genus
*/
public static int countByGenus(Animal[] animals, String genus) {
// your code here
} // countByGenus
Solution
1/**
2 * Counts the number of animals in the given array that belong
3 * to the specified genus. Null arrays, null genus, or null
4 * entries in the array are ignored.
5 *
6 * @param animals an array of {@code Animal} objects
7 * @param genus the genus to count
8 * @return the number of animals matching the specified genus
9 */
10 public static int countByGenus(Animal[] animals, String genus) {
11
12 int count = 0;
13
14 if (animals == null || genus == null) {
15 return 0;
16 } // if
17
18 for (Animal individual : animals) {
19 if (individual != null && genus.equals(individual.getGenus())) {
20 count++;
21 } // if
22 } // for
23
24 return count;
25
26 } // countByGenus