package english; import java.io.File; import java.util.Scanner; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Iterator; import java.util.Set; public class Words { public static <type> void main (String[] args) throws FileNotFoundException { File file=new File("E:\word.txt"); if(!file.exists()){ System.out.println("文件不存在"); return; } Scanner scanner=new Scanner(file); HashMap<String,Integer> hashMap=new HashMap<String,Integer>(); System.out.println("文章-----------------------------------"); while(scanner.hasNextLine()) { String line=scanner.nextLine(); System.out.println(line); 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); } } } System.out.println("统计单词:------------------------------"); Iterator<String> iterator=hashMap.keySet().iterator(); while(iterator.hasNext()) { String word=iterator.next(); System.out.printf("单词:%-12s 出现次数:%d ",word,hashMap.get(word)); } } }
我的代码只做出来了这么多内容,文件的读取和单词出现次数的统计。像标点符号这些,还没有涉及到。
数组用了用,一直出错。排序也没弄出来。晚上电脑一直在调试,但是不运行,真难受。