【问题标题】:Java BufferedReader file IO giving odd, inaccurate outputJava BufferedReader 文件 IO 给出奇怪、不准确的输出
【发布时间】:2014-12-30 19:52:50
【问题描述】:

这里的想法是程序逐个字符地通过一个文本文件,并计算每个字母的出现次数,然后将出现次数存储到一个数组中。但是,我得到了奇怪的、不准确的输出,我似乎无法修复。网上的答案似乎没有帮助。我可能缺少一些非常简单的东西,但我需要在正确的方向上额外推动。

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 包含以下内容:

aaa
aaa
bbb
[];'
abcdefgh qrstuv

我得到以下输出:

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() &gt; -1) { 读取并丢弃!

标签: java io bufferedreader


【解决方案1】:

你忽略了读入的一半字符

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

不要那样做。全部阅读和使用

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

【讨论】:

    【解决方案2】:

    这个

    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 ;  
    }
    

    【讨论】:

    • 感谢你们!有效。我现在明白了,所以我因为调用了两次而把字符扔掉了?
    • @LordValkyrie 确实,你丢掉了 50% 的输入
    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 2020-12-29
    • 2014-01-21
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    相关资源
    最近更新 更多