代码改变世界

软件工程课堂六(《飘》单词统计)

2019-04-28 20:35  一念永恒s  阅读(259)  评论(0编辑  收藏  举报

实现思路:

1.先从文件读取《飘》这篇文章的所有内容

2.获取文章中的单词存入数组中

3.将存入数组的单词进行统计,利用算法计算出单词的数量

4.将统计完成的结果传入文件中

以下是部分代码:

package 统计分析;
  import java.io.*;
  import java.util.*;
  public class tongjifenxi {
  public static <type> void main (String[] args)throws FileNotFoundException {
      File file=new File("D://飘.txt");                  //读取文件
          if(!file.exists()){//如果文件打不开或不存在则提示错误
             System.out.println("文件不存在");
              return;
         }   
         Scanner x=new Scanner(file);
         HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
      while(x.hasNextLine()) {
      String line=x.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);
                 }
           }
       }
        Iterator<String> iterator=hashMap.keySet().iterator();
         int max=0;
         String maxword=null;
         while(iterator.hasNext()){
            String word=iterator.next();
             if(hashMap.get(word)>max) {//比较出现次数最多的单词
                 max=hashMap.get(word);
                 maxword=word; 
           }
         }          System.out.println("本篇文章中出现次数最多的单词是"+maxword);
        System.out.println("共出现了"+max+"次");
    }
private static void calculate(File file, String letter) {
    // TODO 自动生成的方法存根
    
}
 }