2014-11-04 57 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;