读取文本文件,然后执行字符计数并打印每个文件的相对频率

时间:2013-11-19 19:52:25

标签: java for-loop while-loop printf bufferedreader

我正在寻找对文本文件执行字符计数,然后用它与其余字符的相对频率显示每个字符,但我现在只得到空白的控制台。任何帮助将不胜感激。

import java.io.*;


public class RelativeFrequency {

  public static void main(String[] args) throws IOException {

       File file1 = new File("Rf.txt");
       BufferedReader in = new BufferedReader (new FileReader (file1));
           System.out.println("Letter Frequency");

        int nextChar;
        char ch;

        int[] count = new int[26];

        while ((nextChar = in.read()) != -1) {
          ch = ((char) nextChar);
          if (ch >= 'a' && ch <= 'z')
          count[ch - 'a']++;
        }


        for (int i = 0; i < 26; i++) {
          System.out.printf("", i + 'A', count[i]);

        }



in.close();

}

}

2 个答案:

答案 0 :(得分:3)

您的printf语句格式不正确

System.out.printf("%c %d", i + 'A', count[i]);

答案 1 :(得分:3)

您的printf错了

// Assuming you want each letter count on one line
System.out.printf("%c = %d\n", i + 'A', count[i]);

在与tolower

比较之前,您应该在ch上调用if (ch >= 'a' && ch <= 'z')
ch = Character.toLowerCase(ch);