JAVA 无限循环在 Paint 组件上



所以,我有一个程序可以记录并显示哈希表中的碰撞。我已经全部记录了碰撞 - 哪些数据发生了冲突,它应该在哪里,以及它在表中的位置。

问题是油漆组件似乎陷入了无限循环。我无法弄清楚 while 循环的哪一部分。

我尝试删除 while 循环,但这给了我一个编译时错误。我也尝试在 if 语句中输入返回,但这只给了我 x 次崩溃中的 1 个值。

这是我的代码:

     public void paintComponent (Graphics g) {
        int xpos = 20, ypos = 30;
        crash = 0;
        g.setFont(plainfont);
        g.drawString("Hash Crash count is: " + crash, xpos, ypos);
        while(hashtable != null){
            for (String name : names) {
                int start = hashtable.hashFunc3(name);      //locates where data must be
                int end = hashtable.locateCrash(name);      //locates where data is found
                if (start != end) {
                    ypos += 20;
                    crash++;
                    g.drawString("Hash Crash:", xpos, ypos);
                    g.drawString(name, 100, ypos);
                    g.drawString("should be at", 200, ypos);
                    g.drawString(Integer.toString(start), 300, ypos);
                    g.drawString("found at", 350, ypos);
                    g.drawString(Integer.toString(end), 400, ypos);
                    //return;
                }
            }
        }  
    }

非常感谢您的帮助和投入!

找到答案。也许不是最好的,但是...

public void paintComponent (Graphics g) {
    int xpos = 20, ypos = 30;
    crash = 0;
    g.setFont(plainfont);
    g.drawString("Hash Crash count is: " + crash, xpos, ypos);
    while(hashtable != null){
        for (String name : names) {
            int start = hashtable.hashFunc3(name);      //locates where data must be
            int end = hashtable.locateCrash(name);      //locates where data is found
            if (start != end) {
                ypos += 20;
                crash++;
                g.drawString("Hash Crash:", xpos, ypos);
                g.drawString(name, 100, ypos);
                g.drawString("should be at", 200, ypos);
                g.drawString(Integer.toString(start), 300, ypos);
                g.drawString("found at", 350, ypos);
                g.drawString(Integer.toString(end), 400, ypos);
            }
        }
        break; //<-- needed a break; after for loop.
    }  
}

没有将HashMap设置为 null 的转义情况。你需要像if(start == end) hashtable = null;这样的东西来打破循环。

最新更新