Reading a text file then performing a character count and printing the relative frequency of each one

放肆的年华 提交于 2020-01-16 05:13:07

问题


I'm looking to perform a character count on a text file and then display each one with it's relative frequency to the rest of the characters, but I'm presently getting just blank console back. Any help would be greatly appreciated.

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

}

}

回答1:


Your printf statement isn't formatted correctly

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



回答2:


Your printf is wrong

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

Also you should call tolower on ch before comparing with if (ch >= 'a' && ch <= 'z')

ch = Character.toLowerCase(ch);


来源:https://stackoverflow.com/questions/20080766/reading-a-text-file-then-performing-a-character-count-and-printing-the-relative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!