Java 读取文本文件,然后执行字符计数并打印每个字符的相对频率
我希望对一个文本文件执行字符计数,然后显示每个字符与其他字符的相对频率,但我现在得到的只是一个空白控制台。任何帮助都将不胜感激Java 读取文本文件,然后执行字符计数并打印每个字符的相对频率,java,for-loop,while-loop,printf,bufferedreader,Java,For Loop,While Loop,Printf,Bufferedreader,我希望对一个文本文件执行字符计数,然后显示每个字符与其他字符的相对频率,但我现在得到的只是一个空白控制台。任何帮助都将不胜感激 import java.io.*; public class RelativeFrequency { public static void main(String[] args) throws IOException { File file1 = new File("Rf.txt"); BufferedReader in = ne
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语句格式不正确
System.out.printf("%c %d", i + 'A', count[i]);
你的printf是错误的
此外,如果您的printf错误,则在与比较之前,您应该在ch上调用tolower
另外,在比较ch>='a'&&ch%i在java中无效之前,您应该在ch上调用tolower。谢谢,这对它进行了排序。%i在java中无效。谢谢,这对它进行了排序。Cheers,但它在文本文件中都是小写。Cheers,但在文本文件中都是小写。
ch = Character.toLowerCase(ch);