给你个例子吧,楼主可以自己修改一下,通过控制台输入一段英文文章,统计每个单词出现次数 package ex22; import java.util.*;public class CountOccurrenceOfWords { public static void main(String[] args) { // TODO 自动生成方法存根 String text = "Good morning. Have a good class. "+ "Have a good visit. Have fun!";
//Create a TreeMap to hold words as key and count as value TreeMap<String, Integer> map = new TreeMap<String, Integer>();
String[] words = text.split("[ \n\t\r.,;:!?(){]"); for(int i = 0; i < words.length; i++){ String key = words[i].toLowerCase();
if(key.length() > 0){ if(map.get(key) == null){ map.put(key, 1); } else{ int value = map.get(key).intValue(); value++; map.put(key, value); } } }
//Get all entries into a set Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
//Get key and value from each entry for(Map.Entry<String, Integer> entry: entrySet) System.out.println(entry.getValue()+ "\t"+ entry.getKey()); }}
如果要统计每个词出现的次数..用Map吧
package ex22;
import java.util.*;public class CountOccurrenceOfWords {
public static void main(String[] args) {
// TODO 自动生成方法存根
String text = "Good morning. Have a good class. "+
"Have a good visit. Have fun!";
//Create a TreeMap to hold words as key and count as value
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
String[] words = text.split("[ \n\t\r.,;:!?(){]");
for(int i = 0; i < words.length; i++){
String key = words[i].toLowerCase();
if(key.length() > 0){
if(map.get(key) == null){
map.put(key, 1);
}
else{
int value = map.get(key).intValue();
value++;
map.put(key, value);
}
}
}
//Get all entries into a set
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
//Get key and value from each entry
for(Map.Entry<String, Integer> entry: entrySet)
System.out.println(entry.getValue()+ "\t"+ entry.getKey());
}}