// AnimalSounds.java // by Scot Drysdale on 11/25/04 // modified to use Scanner and generics by Scot Drysdale on 5/21/08 // Demonstrates the use of a Map to associate animals with the sounds // that they make. import java.util.*; public class AnimalSounds { public static void main(String args[]) { // A map to play with, initially empty. Map animalMap = new HashMap(); char command = ' '; // a command String animal; // an animal's name String sound; // sound that the animal makes Scanner input = new Scanner(System.in); while (command != 'q') { System.out.print("Command (q, p, g, r, P, ?): "); command = input.nextLine().charAt(0); switch (command) { case 'q': // quit System.out.println("Bye!"); break; case 'p': // put System.out.print("Enter an animal: "); animal = input.nextLine(); if (animal.length() > 0) { System.out.print("Enter the sound that " + getArticle(animal) + " " + animal + " makes: "); sound = input.nextLine(); while (sound.length() <= 0) { System.out.print("Enter the sound that " + getArticle(animal) + " " + animal + " makes: "); sound = input.nextLine(); } animalMap.put(animal, sound); } break; case 'g': // get System.out.print("Enter an animal: "); animal = input.nextLine(); if (animal.length() > 0) { Object obj = animalMap.get(animal); if (obj == null) System.out.println("I do not know the sound that " + getArticle(animal) + " " + animal + " makes."); else System.out.println(toTitleCase(getArticle(animal)) + " " + animal + " says " + obj + "."); } break; case 'r': // remove System.out.print("Enter which animal to remove: "); animal = input.nextLine(); if (animal.length() > 0) animalMap.remove(animal); break; case 'P': // print if (animalMap.isEmpty()) System.out.println("The map is empty"); else { System.out.println("Here are the animals and their sounds:"); Set animalNames = animalMap.keySet(); Iterator iter = animalNames.iterator(); while (iter.hasNext()) { animal = iter.next(); System.out.println(toTitleCase(getArticle(animal)) + " " + animal + " says " + animalMap.get(animal) + "."); } } break; case '?': // print all the commands System.out.println("Commands are\n q: quit\n p: put\n g: get\n " + "r: remove\n P: print\n ?: print all commands\n"); break; default: System.out.println("Huh?"); } } } // Return "an" if the first character of s is a vowel, "a" otherwise. private static String getArticle(String s) { char c = Character.toLowerCase(s.charAt(0)); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') return "an"; else return "a"; } // Return the title-case version of s. private static String toTitleCase(String s) { return Character.toTitleCase(s.charAt(0)) + (s.length() <= 0 ? "" : s.substring(1)); } }