【问题标题】:Reading a text file then performing a character count and printing the relative frequency of each one读取文本文件,然后执行字符计数并打印每个字符的相对频率
【发布时间】:2013-11-19 19:52: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();

}

}

【问题讨论】:

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


    【解决方案1】:

    您的 printf 语句格式不正确

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

    【讨论】:

    • %i 在 java 中无效。
    • 谢谢,整理好了。
    【解决方案2】:

    您的printf 错误

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

    在与if (ch &gt;= 'a' &amp;&amp; ch &lt;= 'z')比较之前,您应该在ch上调用tolower

    ch = Character.toLowerCase(ch);
    

    【讨论】:

    • 干杯,但在文本文件中都是小写的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2021-04-02
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    相关资源
    最近更新 更多