【JAVA】UVA 10420 - List of Conquests

題目原文:https://onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1361

題目大意:按照英文字母順序由小到大排序,先排序國家再計算每個國家愛人人數。

Sample Input

3 愛人的數目
Spain Donna Elvira 國家與愛人的名字
England Jane Doe
Spain Donna Anna

Sample Output

England 1
Spain 2

  1. 按照國家名稱由小而大的順序
  2. 輸出國家的名稱與愛人人數

JAVA MAP

此題可利用java map,下方只提本題會使用到的部分。

創建

Map<String,Integer> map =new HashMap<String, Integer>();

其中鍵值對中的值不可為int,必須為Integer,前者是代表key(關鍵標識符,類似sql中的主鍵),後者代表 value,代表主鍵對應的值

加入值

map.put("A",1);
map.put("B",2); //通過put的方式加入,對應出事創建好的參數類型

判斷

  • 通過key判斷這個值是不是已經存儲,返回一個boolean類型:
map.containsKey("A");
  • 通過value判斷這個值是不是已經存儲:
map.containsValue(2);

增強for循環遍歷

  • 使用keySet()遍歷
for (String key : map.keySet()) {
    System.out.println(key + " :" + map.get(key));
}

🌟程式碼

import java.util.*;
public class main{

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);  
        Map<String, Integer> countries = new TreeMap<String, Integer>();  
        int n = sc.nextInt();  

        while ((n--) > 0) {  
            String country = sc.next();  
            if (!countries.containsKey(country)) {  
                    countries.put(country, 1);  
            }  
            else  
            {  
                countries.put(country, countries.get(country)+1);  
            }  
              
            sc.nextLine();  
        }  
          
        for(String each:countries.keySet())  
        {  
            System.out.println(each+" "+countries.get(each));  
              
        }
	}
}