每日日报

今天做了测验:将txt文件中的字母按比例排序。

代码如下:

package test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Arrays;
public class ZM
{
    public static void main(String[] args)throws IOException
    {
        FileInputStream file=new FileInputStream("e:/王建民/05.StreamAndFileSourceCode/《飘》英文版.txt");
        InputStreamReader isr=new InputStreamReader(file, "gbk");
        StringBuffer sb=new StringBuffer();
        while (isr.ready()) {sb.append((char) isr.read());}
        isr.close();
        file.close();
        String s=sb.toString();
        char c[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','V','Z'};
        int t[]=new int[52];
        Arrays.fill(t, 0);
        for(int i=0;i<s.length();i++){for(int k=0;k<52;k++){if(c[k]==s.charAt(i)){t[k]++;}}}
        double sum=0;
        for(int i=0;i<51;i++)
            for(int k=0;k<51-i;k++)
            {
                if(t[k]<t[k+1])
                {
                    int x=t[k];
                    t[k]=t[k+1];
                    t[k+1]=x;
                    char y=c[k];
                    c[k]=c[k+1];
                    c[k+1]=y;
                }
            }
        DecimalFormat de=new DecimalFormat("0");
        for(int i=0;i<52;i++){sum=sum+t[i];}
        System.out.println("共有"+de.format(sum)+"个字母。");
        System.out.println("各字母频率排名为:");
        DecimalFormat df=new DecimalFormat("0.00"); 
        for(int i=0;i<52;i++)
        {
            double bfb=t[i]*100/sum;
            System.out.println(c[i]+":"+df.format(bfb)+"%");
        }
    }
}

结果如图:

 

posted @ 2020-11-03 19:57  谦寻  阅读(70)  评论(0编辑  收藏  举报