// Helene Martin, CSE 143 // Sample midterm problems. import java.util.*; public class MidtermReview { public static void main(String[] args) { testDashed(); System.out.println(); testByAge(); } // Write a recursive method called printDashed that takes an integer as a // parameter and that prints the integer with dashes in between the digits. // // printDashed(-834) -8-3-4 // printDashed(6) 6 // printDashed(-17) -1-7 // printDashed(-4) -4 // printDashed(983) 9-8-3 // printDashed(42) 4-2 // printDashed(0) 0 // printDashed(29348) 2-9-3-4-8 // Helpful extra cases to write out: // printDashed(342) 3- 4-2 // printDashed(42) 4- 2 // printDashed(2) 2 public static void printDashed(int value) { if (value < 0) { System.out.print("-"); printDashed(-value); } else if (value < 10) { System.out.print(value); } else { printDashed(value / 10); // "rest" of the number printed on the left System.out.print("-"); printDashed(value % 10); // right-most digit printed on the right } } // return a new map with information about people with ages between the min // and max, inclusive. Each key is an integer age, and the value for that // key is a string with the names of all people at that age, separated by // "and" if there is more than one person of that age. Include only ages // between the min and max inclusive, where there is at least one person of // that age in the original map. If the map passed in is // empty, or if there are no people in the map between the min/max ages, // return an empty map. // in: {Paul=28, David=20, Janette=18, Marty=35, Stuart=98, Jessica=35, // Helene=40, Allison=18, Sara=15, Grace=25, Zack=20, Galen=15, Erik=20, // Tyler=6, Benson=48} // byAge(ages, 16, 25): {18=Janette and Allison, 20=David and Zack and Erik, // 25=Grace} public static Map byAge(Map ages, int min, int max) { Map result = new HashMap(); for (String name : ages.keySet()) { int age = ages.get(name); if (min <= age && age <= max) { if (result.containsKey(age)) { result.put(age, result.get(age) + " and " + name); } else { result.put(age, name); } } } return result; } public static void testDashed() { printDashed(-834); // -8-3-4 System.out.println(); printDashed(6); // 6 System.out.println(); printDashed(-17); // -1-7 System.out.println(); printDashed(42); // 4-2 System.out.println(); printDashed(-4); // -4 System.out.println(); printDashed(983); // 9-8-3 System.out.println(); printDashed(0); // 0 System.out.println(); printDashed(29348); // 2-9-3-4-8 } public static void testByAge() { Map people = new HashMap(); people.put("Paul", 28); people.put("David", 20); people.put("Janette", 18); people.put("Marty", 35); people.put("Stuart", 98); people.put("Jessica", 35); people.put("Helene", 40); people.put("Allison", 18); people.put("Sara", 15); people.put("Grace", 25); people.put("Zack", 20); people.put("Galen", 15); people.put("Erik", 20); people.put("Tyler", 6); people.put("Benson", 48); Map result = byAge(people, 16, 25); System.out.println(result); } }