❶ java編程:輸入一段英文:1、統計一共有多少個單詞;2、每個單詞出現的次數;3、按出現次數升或降序排列
自己去調整,隨便寫的;
package com..com.java;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MatchWorld {
public static void main(String[] args) {
String str = "Is there anyone who hasn't suffered for the secret love? We alwaysthink that"
+ " love is very heavy, heavy and could be the heaviest thing inthe world. "
+ "But one day, when you look back, you suddenly realize thatit's always light, "
+ "light. We all thought love was very deep, but infact it's very thin. " + "The deepest and heaviest love must grow up withthe time";
// 全部轉換成大寫
str = str.toUpperCase();
//或許你可以考慮用空格分割
String[] rang = str.split("\\b");
// 自己去調整吧,如果要得到精確的
System.out.println("單詞總數大概為:" + rang.length);
// 用來記錄的單詞
Map<String, Integer> map = new HashMap<String, Integer>();
int countSpace = 0;
//統計各個字元出現的次數
for (String s : rang) {
if (s.trim().length() > 0) {
s = s.trim();
if (!map.containsKey(s)) {
int count = str.split("\\b" + s.trim() + "\\b").length;
map.put(s, count);
}
} else {
map.put("空格", countSpace++);
}
}
//單詞出現次數
for (String key : map.keySet()) {
System.out.println(key + "出現:" + map.get(key) + "次");
}
//把元素添加到list
List<String> list = new ArrayList<String>();
list.addAll(map.keySet());
// 排序前
System.out.println("\n排序前:\n");
for (String s : list) {
System.out.println(s+"出現次數:"+map.get(s));
}
// 開始排序
System.out.println("\n按照出現次數降序排列(AESC):\n");
for (int i = 1; i < list.size(); i++) {
for (int j = 0; j < list.size() - i; j++) {
if (map.get(list.get(j)) > map.get(list.get(j+1))) {
String tmp = list.get(j);
list.set(j, list.get(j+1));
list.set(j + 1, tmp);
}
}
}
// 排序後
System.out.println("\n排序後:\n");
for (String s : list) {
System.out.println(s+"出現次數:"+map.get(s));
}
}
}