要求:输出某个英文文本文件中 26 字母出现的频率,由高到低排列,并显示字母出现的百分比,精确到小数点后面两位。
代码:
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileReader; 4 import java.io.IOException; 5 import java.util.Scanner; 6 7 public class tongJi { 8 public static void main(String[] args) throws IOException { 9 File file = new File("D:\Harry Potter\harry potter\Harry Potter and the Sorcerer's Stone.txt"); 10 if (!file.exists()) { 11 System.out.println("文件不存在"); 12 return; 13 } 14 BufferedReader buf = new BufferedReader(new FileReader(file)); 15 16 int[] num = new int[100]; 17 char[] ying = new char[100]; 18 String s = buf.readLine(); 19 while (s != null) { 20 if (s.equals("exit")) { 21 System.out.println("文件存在"); 22 System.exit(1); 23 } else { 24 String[] lineWords = s.split(" "); 25 for (int i = 0; i < lineWords.length; i++) { 26 for (int j = 0; j < lineWords[i].length(); j++) { 27 if (lineWords[i].charAt(j) >= 'A' && lineWords[i].charAt(j) <= 'Z') 28 num[lineWords[i].charAt(j) - 'A' + 1]++; 29 else if (lineWords[i].charAt(j) >= 'a' && lineWords[i].charAt(j) <= 'z') 30 num[lineWords[i].charAt(j) - 'a' + 1 + 24]++; 31 } 32 } 33 s = buf.readLine(); 34 35 } 36 } 37 char a = 'A'; 38 char b = 'a'; 39 for (int i = 1; i <= 52; i++) { 40 if (i <= 26) 41 ying[i] = a++; 42 else 43 ying[i] = b++; 44 } 45 46 47 int sum = 0; 48 for (int i = 1; i <= 52; i++) { 49 sum += num[i]; 50 } 51 52 for (int i = 1; i <= 52; i++) { 53 for (int j = i + 1; j <= 52; j++) { 54 if (num[i] < num[j]) { 55 int t = num[i]; 56 num[i] = num[j]; 57 num[j] = t; 58 59 char m = ying[i]; 60 ying[i] = ying[j]; 61 ying[j] = m; 62 } 63 } 64 } 65 System.out.println("字母总数:"+sum); 66 System.out.println("按频率从大到小排列:"); 67 for (int i = 1; i <= 52; i++) { 68 double ans = num[i] * 1.0 / sum * 100; 69 System.out.println(ying[i] + " frequency is " + String.format("%.2f", ans) + "%"); 70 71 } 72 } 73 }