牛马不精神 2021-05-05 20:32 采纳率: 0%
浏览 96

java树越界问题。

    public HuffmanTree(int[] weights) {
        this.charset = "";
        for (int i = 0; i < weights.length; i++)
            this.charset += (char) ('A' + i);
        int n = weights.length;
        this.huftree = new TriElement[2 * n - 1];
        for (int i = 0; i < n; i++)
            this.huftree[i] = new TriElement(weights[i]);

        for (int i = n; i < 2 * n - 1; i++) {
            int min1 = Integer.MAX_VALUE, min2 = min1;
            int x1 = -1, x2 = -1;
            for (int j = 0; j < i; j++) {
                if (this.huftree[j].parent == -1) {
                    if (this.huftree[j].data < min1) {
                        min2 = min1;
                        x2 = x1;
                        min1 = this.huftree[j].data;
                        x1 = j;
                    } else if (this.huftree[j].data < min2) {
                        min2 = huftree[j].data;
                        x2 = j;
                    }
                }
            }
            this.huftree[x1].parent = i;
            this.huftree[x2].parent = i;
            this.huftree[i] = new TriElement(min1 + min2, -1, x1, x2);
        }
    }

    private String getCode(int i) {
        int n = 10;
        char hufcode[] = new char[n];
        int child = i, parent = this.huftree[child].parent;
        for (i = n - 1; parent != -1; i--) {
            hufcode[i] = (huftree[parent].left == child) ? '0' : '1';
            child = parent;
            parent = huftree[child].parent;

        }
        return new String(hufcode, i + 1, n - 1 - i);

    }

    public String toString() {
        String str = "Huffman树的节点";
        for (int i = 0; i < this.huftree.length; i++)
            str += this.huftree[i].toString() + ",";
        str += "\nHuffman编码";
        for (int i = 0; i < this.charset.length(); i++) {
            str += this.charset.charAt(i) + ":" + getCode(i) + ",";
        }
        return str;
    }

    public static void main(String[] args) {
        String text = "abde";
        int[] A = { 7, 5, 1, 2 };
        HuffmanTree ht = new HuffmanTree(A);
        System.out.println(ht.toString());
    }

 

报错信息

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at shujujiegou.HuffmanTree.<init>(HuffmanTree.java:33)
    at shujujiegou.HuffmanTree.main(HuffmanTree.java:67)
 

  • 写回答

1条回答 默认 最新

  • miaoch 2023-02-22 15:57
    关注

    无非就是x1在某种情况下是-1呗,自己卡断点调试看看不就知道了

    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制