一、題目描述
二、基本思路
通過FileReader讀取到文件,通過readLine讀取字符串,拆成字符進行判斷,這裏使用最笨的方法用大小為52的數組存儲各個字母出現的頻次,通過ascii碼聯係數字與字母,排序後輸出即可。
三、源碼及結果
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileReader; 4 import java.text.DecimalFormat; 5 6 public class sumNovel { 7 8 public static void main(String[] args) { 9 // TODO Auto-generated method stub 10 File f = new File("Harry Potter and the Sorcerer's Stone.txt"); 11 FileReader fr = null; 12 BufferedReader br = null; 13 try { 14 DecimalFormat df = new DecimalFormat("0.00"); 15 fr = new FileReader(f); 16 br = new BufferedReader(fr); 17 String str = null; 18 double[] sum = new double[52]; 19 double[] result = new double[52]; 20 int[] order = new int[52]; 21 for(int i=0;i<52;i++) 22 { 23 sum[i] = 0; 24 order[i] = i; 25 } 26 double all = 0; 27 while((str = br.readLine())!=null) 28 { 29 char[] array = str.toCharArray(); 30 for(int i=0;i<array.length;i++) 31 { 32 int x = Integer.valueOf(array[i]); 33 if(x>=65&&x<=90) 34 { 35 int j=x-65; 36 sum[j]++; 37 all++; 38 }else if(x>=97&&x<=122) 39 { 40 int j=x-97+26; 41 sum[j]++; 42 all++; 43 } 44 } 45 } 46 for(int i=0;i<52;i++) 47 { 48 result[i] = sum[i]/all; 49 } 50 51 for (int i = 0; i < 52; i++) { 52 int maxIndex = i; 53 for (int j = i; j < 52; j++) { 54 if (result[order[j]] > result[order[maxIndex]]) 55 maxIndex = j; 56 } 57 int temp = order[maxIndex]; 58 order[maxIndex] = order[i]; 59 order[i] = temp; 60 } 61 for(int i=0;i<52;i++) 62 { 63 if(order[i]>=0&&order[i]<=25) 64 { 65 double j = order[i]+65; 66 char e = (char)j; 67 System.out.print(e+":"); 68 }else{ 69 double j = order[i]+97-26; 70 char e = (char)j; 71 System.out.print(e+":"); 72 } 73 double x = result[order[i]]*100; 74 System.out.println(df.format(x)+"%"); 75 } 76 77 } catch (Exception e) { 78 // TODO: handle exception 79 } 80 } 81 82 }