单词个数统计上机实验

   今天的上机以自学为主,以为实在对文件处理一点以不会。学会了对文件的读入和输出等,完整代码还不完成,以下为一部分,还不够完整成熟。

设计思路:

1 文件读入

2 单词之间是以空格隔开的,以此来截取单词

3 进行相同单词的比较统计

4输出单词的个数

源代码(部分):

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

 

public classTest {

     public static void main(String[] args) {


         BufferedReaderbr = null;

         try {

              Map<String,Integer>map = newHashMap<String,Integer>();

              br = new BufferedReader(new FileReader("d:/mywords.txt"));

              Stringline;

              while(null != (line = br.readLine())){

                   System.out.println(line);



                   String[]ss = line.split("\\s+");

                   for(String s : ss){

                       if(map.containsKey(s)){

                            map.put(s, map.get(s)+1);

                       }else{

                            map.put(s, 1);

                       }

                   }

              }

              Set<String>keys = map.keySet();

              for(String key : keys){

                   System.out.println(key + "有:" + map.get(key) + "个.");

              }

         }catch(FileNotFoundException e) {

              e.printStackTrace();

         }catch(IOException e) {

              e.printStackTrace();

         }finally {

              if(null != br){

                   try {

                       br.close();

                   }catch(IOException e) {

                       e.printStackTrace();

                   }

              }

         }

     }

}

  

猜你喜欢

转载自www.cnblogs.com/xuange1/p/9775661.html