這裏的想法是,程序按字符通過文本文件逐個進行計數,然後計算每個字母的出現次數,然後將出現次數存儲到數組中。但是,我收到奇怪的,不準確的輸出,我似乎無法修復。在線答案似乎沒有幫助。這可能是我錯過的一件很簡單的事情,但我需要向正確的方向額外推動。Java BufferedReader文件IO給出奇數,不準確的輸出
char token;
char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int[] occurences = new int[25];
BufferedReader inFile = new BufferedReader(new FileReader("plaintext.txt"));
while (inFile.read() > -1) {
token = (char)inFile.read();
for (int i = 0; i < alphabet.length; i++) {
if (Character.compare(token, alphabet[i]) == 0) {
occurences[i] += 1;
}
}
}
for (int i = 0; i < occurences.length; i++) {
System.out.println(occurences[i]);
}
inFile.close();
因爲plaintext.txt包含以下內容:
我得到以下輸出:
3
1
1
0
1
0
1
0
0
0
0
0
0
0
0
0
0
1
0
1
0
1
0
0
0
提前感謝!
你忽略了許多字符的讀取,不這樣做!這,'while(inFile.read()> -1){'讀取並丟棄! – 2014-11-04 01:49:43