2015-06-02 30 views
-3

我想編寫一種將數據分發到「年齡」類別的主要方法。 每個數據項有年齡和年齡。年齡分類跨越5年,所以0-5,5-10,10-15等 我只想顯示其中的項目的類別。在任意數量的類別中均勻分配項目

所以,如果輸入的是:

理查德,15

海倫,24

史蒂芬,16

埃德溫,19

弗雷德裏克12

輸出將如下所示:

計算的類別:

0-5,5-10,10-15,15-20,20-25

分佈:

10-15:弗雷德裏克

15 -20:理查德,史蒂芬,埃德溫

20-25:海倫

+0

什麼是問題/你有什麼嘗試? – Reimeus

+0

'HashMap >'是你的朋友。您至少應該發佈您嘗試的代碼,並指定問題所在。 – membersound

+0

至少嘗試好友... – CoderNeji

回答

1
public static void main(String[] args) throws IOException { 
    Map<Integer, List<String>> result = new HashMap<Integer, List<String>>(); 
    while (true) { 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     String line = br.readLine(); 
     if (!line.contains(",")) { 
      System.out.println("incorrect input string"); 
      continue; 
     } 

     String name = line.split(",")[0]; 
     String age = line.split(",")[1]; 
     age = age.trim(); 
     int ageInt = -1; 
     try { 
      ageInt = Integer.parseInt(age); 
     } catch (NumberFormatException e) { 
      System.out.println("age not a number"); 
      continue; 
     } 

     ageInt = ageInt - ageInt % 5; 
     List<String> names = result.get(ageInt); 
     if (names == null) { 
      names = new ArrayList<String>(); 
     } 
     names.add(name); 
     result.put(ageInt, names); 

     printResult(result); 
    } 
} 

private static void printResult(Map<Integer, List<String>> result) { 
    List<Integer> ages = new ArrayList<Integer>(); 
    ages.addAll(result.keySet()); 
    Collections.sort(ages); 

    for (Integer integer : ages) { 
     List<String> name2 = result.get(integer); 
     System.out.println(integer + " - " + (integer + 5) + " : "); 
     for (String s : name2) { 
      System.out.println("  " + s); 
     } 
    } 
} 
+0

問題在哪裏? – Bendy