[英]Reading a text file then performing a character count and printing the relative frequency of each one
我希望對文本文件進行字符計數,然后以相對於其余字符的相對頻率顯示每個字符,但是目前我只能得到空白的控制台。 任何幫助將不勝感激。
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();
}
}
您的printf語句格式不正確
System.out.printf("%c %d", i + 'A', count[i]);
您的printf
錯誤
// Assuming you want each letter count on one line
System.out.printf("%c = %d\n", i + 'A', count[i]);
另外,在與if (ch >= 'a' && ch <= 'z')
比較之前,您應該在ch上調用tolower
ch = Character.toLowerCase(ch);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.