2014-11-04 67 views
0

這裏的想法是,程序按字符通過文本文件逐個進行計數,然後計算每個字母的出現次數,然後將出現次數存儲到數組中。但是,我收到奇怪的,不準確的輸出,我似乎無法修復。在線答案似乎沒有幫助。這可能是我錯過的一件很簡單的事情,但我需要向正確的方向額外推動。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 

提前感謝!

+0

你忽略了許多字符的讀取,不這樣做!這,'while(inFile.read()> -1){'讀取並丟棄! – 2014-11-04 01:49:43

回答

1

while (inFile.read() > -1) { 
    token = (char)inFile.read(); 

翻譯爲:讀一個字符,將其丟棄。讀另一個,對待它。多讀一個,丟棄等

你可以得到靈感here - 本質:

int c; 
while ((c = inFile.read()) != -1) { 
    // there's no need to declare token before this loop 
    char token = (char) c ; 
} 
+0

感謝你們兩位!有效。我現在明白了,所以我把這個角色扔掉了,因爲它調用了兩次? – LordValkyrie 2014-11-04 02:03:35

+0

@LordValkyrie事實上,你扔掉了50%的輸入 – fvu 2014-11-04 02:05:05

1

你忽略了一半的字符閱讀與

while (inFile.read() > -1) { 
    token = (char)inFile.read(); 

不要那樣做。閱讀和使用它們

int intToken = 0; 
while ((intToken = inFile.read()) > -1) { 
    token = (char)intToken;