课堂练习

package test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
   
public class W1 {
  
    public static void main(String[] args) throws IOException {
        try {
            //IO操作读取文件内容
            FileReader fr = new FileReader("d:\\文件\\单词.txt");
            BufferedReader br = new BufferedReader(fr);
            NumberFormat nf = NumberFormat.getInstance();
               
            // 设置精确到小数点后2位
       
            nf.setMaximumFractionDigits(2);
            HashMap<String, Integer> map = new HashMap<String, Integer>();
              
            String string =null;
            Integer count = 0;//每个字母的次数
            Integer total = 0;//总共多少个字母
              
            while ((string=br.readLine())!=null) {
                char[] ch = string.toCharArray();
                  
                for (int i = 0; i < ch.length; i++) {
                    if (ch[i] > 'A' && ch[i]< 'z') {
                          
                    total++;
                    ch[i] = Character.toLowerCase(ch[i]);
                    count = map.get(ch[i]+"");
                    if (count == null) {
                        count = 1;
                    }else {
                        count++;
                    }
                    map.put(ch[i]+"", count);
                }
                }
            }
             ArrayList<String> list = new ArrayList<String>();
             list.addAll(map.keySet());  //将单词添加到list中
               
             //排序按照出现次数降序排列
             for(int i = 0;i < list.size();i++)
             {
                   
                 for(int j = 0;j < (list.size() - i-1);j++)     //list.size() - i-1因为要用到i+1要考虑是否超出范围的问题
                 {
                       
                     if(map.get(list.get(j)) < map.get(list.get(j+1)))
                     {
                         String t = list.get(j);
                         list.set(j, list.get(j+1));
                         list.set( j+1, t);
                     }
                 }
             }
             for(int i = 0 ; i < list.size();i++)
                {
                    System.out.println(list.get(i) + ":" + map.get(list.get(i)) +"   "+ nf.format((float)(map.get(list.get(i)))*100/total) + "%");
                }
              
              
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
      
      
      
      
}

 

posted @ 2019-05-04 22:45  Triassic  阅读(147)  评论(0编辑  收藏  举报