为什么BufferedReader read()获取额外的字符

时间:2017-10-20 19:43:27

标签: java bufferedreader

我正在创建一个Huffman Encode方法,该方法使用缓冲读取器来读取文件,将新的char值添加到名为'characters [128]'的数组中,如果char已经存在于'characters [128]'中,那么1被添加到该char的频率/计数(我在charCount [128]中存储在与char相同的索引处)。我将附加我的代码,但是当我运行它时,它会打印出一个未知的char()作为最后一个char,这意味着它会比它应该晚一个迭代停止while循环。你知道为什么,以及我如何解决这个问题?

public Playground() {
    char c;
    int size = 0;
    char[] characters = new char[128];
    int[] charCount = new int[128];
    BufferedReader br = null;
    try {   
        br = new BufferedReader(new FileReader("input.txt"));
        while ((c = (char)br.read()) != -1) {
            for (int i = 0; i <= size; ++i) {
                if (size == 0) {
                    characters[i] = c;
                    charCount[i]++;
                    size++;
                    System.out.println("Letter/Count: " + characters[i] + "/" + charCount[i]);
                    break;
                }
                if (characters[i] == c) {
                    charCount[i]++;
                    break;
                } else if (i == size) {
                    characters[i] = c;
                    charCount[i]++;
                    size++;
                    System.out.println("Letter/Count:"+characters[i]+"/" + charCount[i]);
                    break;
                }
            }
        }
        br.close();
    } catch (IOException e){
        System.out.println("IOEXCEPTION: " + e);
    }
}
public static void main(String args[]) {
    System.out.println("Main Is Working");
    Playground p = new Playground();
    System.out.println("Constructor is not");
}

1 个答案:

答案 0 :(得分:0)

问题在于您将int转换为char,然后再将其与int -1进行比较。做这样的事情: -

TBEstados