1. 程式人生 > 實用技巧 >讀取檔案,計算字母出現次數和頻率,按順序列印

讀取檔案,計算字母出現次數和頻率,按順序列印

用BufferedReader類讀取檔案,陣列記錄次數,冒泡法排序,最後列印

 

package test01;

import java.io.*;
import java.util.*;
import java.text.DecimalFormat;

public class Zimu0 {

    public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\piao.txt")));
        
int[] count = new int[52]; char[] c = new char[1]; int len = br.read(c); while(len!=-1) { if(c[0]<='Z'&&c[0]>='A') { int number = c[0]; count[number-65]++; } else if(c[0]<='z'&&c[0]>='a') {
int number = c[0]; count[number-71]++; } len = br.read(c); } Print(count); br.close(); } public static int add(int[] count) { int sum=0; for(int i=0;i<count.length;i++) { sum += count[i]; }
return sum; } public static void Print(int[] count) { int sum=add(count); char [] b = new char[52]; DecimalFormat df= new DecimalFormat("######0.00"); for(int i=0;i<52;i++) { char abc; if(i<26){ abc = (char)(i+65); } else { abc = (char)(i+71); } b[i]=abc; } for(int i=0;i<b.length-1;i++) { for(int j=0;j<b.length-i-1;j++) { if(count[j]<count[j+1]) { int t=count[j]; count[j]=count[j+1]; count[j+1]=t; char y=b[j]; b[j]=b[j+1]; b[j+1]=y; } } } System.out.println("字母\t次 數\t佔 比"); for(int i=0;i<52;i++) { System.out.println(b[i]+":\t"+count[i]+"\t"+df.format((double)100*count[i]/sum)+"%"); } } }