(java)统计若干段英文中的单词数量,并统计每个单词出现的次数按降序排序。


1单词之间以空格(1个或多个空格)为间隔。
2忽略空行或者空格行。

输入说明:

若干行英文,最后以!!!!!为结束。

输出说明:

单词数量
出现次数排名前10的单词(次数按照降序排序,如果次数相同,则按照键值的字母升序排序)及出现次数。


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class nd2question {

	public static void main(String[] args) throws IOException {
		
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String S = "";
		while(true){
			String s = in.readLine();
			if (!"!!!!!".equals(s)) {
				S += s + " ";
			}
			else break;
		}
		
		S = S.replaceAll("( )+", " ");
		String str[] = S.split(" ");
		
		System.out.println(str.length);
		
		Map <String, Integer> map = new HashMap<String, Integer>();
		
        for (String s1 : str) {
        	
        	if (!map.containsKey(s1))  
                map.put(s1, 1);  
            else  
                map.put(s1, (map.get(s1)+1));  
		}

      
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        	
            public int compare(Map.Entry<String, Integer> mapping2, Map.Entry<String, Integer> mapping1) 
            {
                return mapping1.getValue().compareTo(mapping2.getValue());
            }
        });
     
        Map.Entry<String, Integer> mapping = null;
        for (int i = 0 ;i<list.size() ;i++) {
        	mapping = list.get(i);
        	if (i<10)
            System.out.println(mapping.getKey() + "=" + mapping.getValue());
        }
	}
}

猜你喜欢

转载自blog.csdn.net/wangeru/article/details/80782387