我正在尋找對java中所有小寫字符.txt文件執行字符計數,目前打印方法在嘗試打印計數時最終爲空。任何幫助將不勝感激。文本文件的字符數
public static void main(String[] args) throws IOException {
File file1 = new File("newfile.txt");
BufferedReader in = new BufferedReader (new FileReader (file1));
System.out.println("Relative Letter Frequency");
int ch;
char i = 0;
// Declare 26 char counting
int[] count = new int[26];
//Loop through the file char
while ((ch = in.read()) != -1) {
i = (char) ch;
if (i >= 'a' && i <= 'z')
count[i - 'a']++;
}
//Print loop
for (int j = 0; j < 26; j++) {
//Print formatting so each letter is represented on
//a new line with correct spacing
System.out.printf("%c %d \n", j + 'a', count[j]);
System.out.println();
}
in.close();
}
int Counter(File file,String Charset) throws IOException {
File file1 = new File("newfile.txt");
BufferedReader in = new BufferedReader(new FileReader(file1));
int Count = 0;
while (in.read() > -1){
Count++;
}
System.out.println(Count);
in.close();
return Count;
}
}
我試圖更改字符計數器的循環,但依然無果
public void Counter(File file,String Charset) throws IOException {
File file1 = new File("newfile.txt");
BufferedReader in = new BufferedReader(new FileReader(file1));
int CH;
char k = 0;
int [] Count = new int [1];
while ((CH = in.read()) != -1){
k = (char) CH;
if (k >= 'a' && k <='z')
Count [k]++;
}
System.out.println(Count[k]);
in.close();
}
你可以通過字符的字節大小來劃分文件大小嗎? – Discipol
對我來說工作得很好,究竟是什麼問題? @Discipol'in.read()'讀取字節,所以它應該分開;} – Ishtar
@Discipol如果將文件大小除以字符的字節大小,這也包括空格和新行標記。 – user3008724