2017-05-23 45 views
0

所以,我有一個程序可以記錄並顯示散列表中的衝突。我已經記錄了所有的碰撞 - 數據相撞,應該在哪裏,以及在哪裏。JAVA無限循環上油漆組件?

問題是paintcomponent似乎卡在一個無限循環中。我無法弄清楚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; 
       } 
      } 
     } 
    } 

您的幫助和投入是非常感謝!

+0

什麼設置散列表爲空值? –

+0

什麼類的類型是'hashtable'變量,並且當這個條件將被滿足while(hashtable!= null)'?從顯示的代碼幾乎不可能說出錯的地方。 – MaxZoom

+0

'if(hashtable!= null)'而不是'while'。很明顯,哈希表稍後做出。 –

回答

0

有沒有逃生的情況下,HashMap設置爲null。你需要類似if(start == end) hashtable = null;來打破循環。

0

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

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. 
    } 
} 
+0

「需要休息一下;循環之後」。然後你不需要循環。 'if(hashtable!= null)'。 –