统计文章中各个英语单词出现的次数:
import java.io.*; import java.util.*; public class Tongji { public static <type> void main (String[] args) throws FileNotFoundException { File file=new File("D:\\english.txt"); //读取文件 Scanner input=new Scanner(file); HashMap<String,Integer> hashMap=new HashMap<String,Integer>(); while(input.hasNextLine()) { String line=input.nextLine(); String[] lineWords=line.split("\\W+"); Set<String> wordSet=hashMap.keySet(); for(int i=0;i<lineWords.length;i++) { if(wordSet.contains(lineWords[i])) { Integer number=hashMap.get(lineWords[i]); number++; hashMap.put(lineWords[i], number); } else { hashMap.put(lineWords[i], 1); } } } for (String key : hashMap.keySet()) { System.out.println(key+"出现:"+hashMap.get(key)+"次"); } } }
结果:
原文:https://www.cnblogs.com/zwang/p/10815693.html