import java.util.*; import java.io.*; public class MedalCount { public static void main(String[] args) throws IOException { PrintStream output = System.out; Map goldMedals = new TreeMap(); Map silverMedals = new TreeMap(); Map bronzeMedals = new TreeMap(); // read the input using a scanner final String INPUT_NAME = "medals.txt"; Scanner in = new Scanner(new File(INPUT_NAME)); while (in.hasNextLine()) { String line = in.nextLine(); if (line.isEmpty()) { continue; } String regex = ","; String[] s = line.split(regex); // constants to index into s final int EVENT = 0; final int GOLD = 1; final int SILVER = 2; final int BRONZE = 3; String event = s[EVENT]; String goldCountry = s[GOLD]; String silverCountry = s[SILVER]; String bronzeCountry = s[BRONZE]; // Update gold medal country by adding 1 to their // gold medal counts; also, add the countries to // the silverMedals and bronzeMedals maps if necessary Integer oldGold = goldMedals.get(goldCountry); if (oldGold == null) { oldGold = 0; } goldMedals.put(goldCountry, oldGold + 1); if (silverMedals.get(goldCountry) == null) { silverMedals.put(goldCountry, 0); } if (bronzeMedals.get(goldCountry) == null) { bronzeMedals.put(goldCountry, 0); } // Update silver medal country by adding 1 to their // silver medal counts; also, add the countries to // the goldMedals and bronzeMedals maps if necessary Integer oldSilver = silverMedals.get(silverCountry); if (oldSilver == null) { oldSilver = 0; } silverMedals.put(silverCountry, oldSilver + 1); if (goldMedals.get(silverCountry) == null) { goldMedals.put(silverCountry, 0); } if (bronzeMedals.get(silverCountry) == null) { bronzeMedals.put(silverCountry, 0); } // Update bronze medal country by adding 1 to their // bronze medal counts; also, add the countries to // the goldMedals and silverMedals maps if necessary Integer oldBronze = bronzeMedals.get(bronzeCountry); if (oldBronze == null) { oldBronze = 0; } bronzeMedals.put(bronzeCountry, oldBronze + 1); if (goldMedals.get(bronzeCountry) == null) { goldMedals.put(bronzeCountry, 0); } if (silverMedals.get(bronzeCountry) == null) { silverMedals.put(bronzeCountry, 0); } } // YOUR CODE GOES HERE TO OUTPUT THE RESULTS // Gold medal counts: // Find the unique gold medal counts by putting the goldMedal // values into a TreeSet TreeSet ascendingGoldCounts = new TreeSet(goldMedals.values()); // Reverse the set so that we get the unique gold medal counts // in descending order (from largest to smallest) Set goldCounts = ascendingGoldCounts.descendingSet(); // For each number of gold medals won (from largest to smallest) for (Integer numGold : goldCounts) { // Find the countries that won numGold for (String country : goldMedals.keySet()) { Integer thisGold = goldMedals.get(country); if (thisGold.equals(numGold)) { Integer thisSilver = silverMedals.get(country); Integer thisBronze = bronzeMedals.get(country); output.printf("%25s %2s %2s %2s%n", country, thisGold.toString(), thisSilver.toString(), thisBronze.toString()); } } } } }