问题
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