Reading a text file then performing a character co

2019-08-14 07:34发布

问题:

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