代码之家  ›  专栏  ›  技术社区  ›  Charlotte K

为什么BufferedReader read()会拾取额外字符

  •  0
  • Charlotte K  · 技术社区  · 8 年前

    我正在创建一种哈夫曼编码方法,该方法使用缓冲读取器读取文件,将新的字符值添加到名为“characters[128]”的数组中,如果字符已经存在于“characters[128]”中,则将1添加到该字符的频率/计数(我将其存储在charCount[128]中,与该字符的索引相同)。我将附加我的代码,但当我运行它时,它会为最后一个字符打印出一个未知的字符(),这意味着它会比应该的时间晚一次停止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 回复  |  直到 8 年前
        1
  •  0
  •   Max08    8 年前

    问题是,您正在将int转换为char,然后再次将其与int-1进行比较。这样做:-

    int i = -1;
    while ((i = br.read()) != -1) {
         char c = (char)i;
         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;
            }
        }
    }