at90

Population Counter

May 25th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class PopulationCounter {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.  
  7.  
  8.         String command;
  9.         Map<String, Country> countries = new TreeMap<>();
  10.  
  11.         while (!"report".equals(command = scanner.nextLine())) {
  12.             String[] countryTokens = command.split("\\|");
  13.             String cityName = countryTokens[0];
  14.             String countryName = countryTokens[1];
  15.             int population = Integer.valueOf(countryTokens[2]);
  16.  
  17.             Country country = new Country(countryTokens[1]);
  18.  
  19.             if (!countries.containsKey(countryName)) {
  20.                 country.cities.put(cityName, population);
  21.                 country.population = population;
  22.  
  23.                 countries.put(countryName, country);
  24.             } else {
  25.                 for (Map.Entry<String, Country> countryKey : countries.entrySet()) {
  26.                     if (countryName.equals(countryKey.getKey())) {
  27.                         countryKey.getValue().cities.put(cityName, population);
  28.                         countryKey.getValue().addPopulation(population);
  29.                         countries.put(countryName, countryKey.getValue());
  30.                     }
  31.                 }
  32.             }
  33.         }
  34.  
  35.         for (Map.Entry<String, Country> country : countries.entrySet()) {
  36.             System.out.printf("%s (total population: %d)%n", country.getKey(), country.getValue().population);
  37.             for (Map.Entry<String, Integer> city : country.getValue().cities.entrySet()) {
  38.                 System.out.printf("=>%s: %d%n", city.getKey(), city.getValue());
  39.             }
  40.         }
  41.     }
  42.  
  43.     private static class Country {
  44.         public String name;
  45.         public Map<String, Integer> cities;
  46.         public int population;
  47.  
  48.         public Country() {
  49.         }
  50.  
  51.         public Country(String name) {
  52.             this.name = name;
  53.             this.cities = new LinkedHashMap<>();
  54.         }
  55.  
  56.         public void addPopulation(int population) {
  57.             this.population += population;
  58.         }
  59.  
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment