读取文本文件然后进行字符计数和打印每一个的相对频率(Reading a text file then

2019-10-19 00:25发布

我期待的文本文件进行字符数,然后显示每一个与它的相对频率的字符的其余部分,但我目前得到只是空白控制台回来。 任何帮助将不胜感激。

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();

}

}

Answer 1:

你的printf语句格式不正确

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


Answer 2:

printf是错误的

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

还应该调用tolower上通道与比较之前if (ch >= 'a' && ch <= 'z')

ch = Character.toLowerCase(ch);


文章来源: Reading a text file then performing a character count and printing the relative frequency of each one