2010-06-07 151 views
1

一段時間以來,我一直在研究一個將值散列到散列表中的程序(我不記得具體情況,具體細節本身與問題無關)。不管怎麼說,我有下面的代碼爲「recordInput」方法的一部分:變量賦值和循環

tempElement = new hashElement(someInt); 

    while(in.hasNext() == true) 
    { 
     int firstVal = in.nextInt(); 
     if (firstVal == -911) 
     { 
      break; 
     } 
     tempElement.setKeyValue(firstVal, 0); 
     for(int i = 1; i<numKeyValues;i++) 
     { 
      tempElement.setKeyValue(in.nextInt(), i); 
     } 

     elementArray[placeValue] = tempElement; 
     placeValue++; 

    } // close while loop 

} // close method 

的這部分代碼是給我一個非常討厭的錯誤 - 無論我怎麼finagled它,無論我所付出的投入該程序,它總是會產生一個只有一個值的數組 - 最後一個。

問題,正如我後來確定的那樣,是因爲我沒有在循環中創建tempElement變量,並且因爲在循環結束之前沒有將值分配給elementArray[] - 每個術語都定義爲「tempElement」 - 當循環結束時,數組中的每個插槽都充滿了tempElement所拍攝的最後一個值。

我能夠通過在while循環中移動tempElement的聲明來修復此錯誤。我的問題,Stackoverflow,是否有另一種(更好的)方法來避免這個bug,同時保持tempElement的變量聲明在while循環之外。

+1

你最好了解Java編碼慣例:http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html。類名應以大寫字母開頭。 – 2010-06-07 15:31:28

回答

2

爲什麼要在while循環之外保留變量聲明?無論如何,只要你每次將它分配給一個新的hashElement:

hashElement tempElement; 
while (/*...*/) { 
    tempElement = new hashElement(); 
    //... 

雖然這當然不是「更好」。一般來說,儘量縮小範圍。

1

這不是關於變量的聲明,而是關於你創建的對象。 java中的數組僅將引用指向對象,因此如果實際上想要在數組中有不同的對象,則需要在循環中的某處使用new創建它們。

tempElement = new WhateverClass(); 
+0

或者只是'elementArray [placeValue] = new ...'並且完全跳過臨時變量。 – 2010-06-07 15:32:26

+0

不是當你打電話給它的人。調用setArray [placeValue] .setWhatever(whatever)這樣的setter是醜陋的,應該受到嚴厲的懲罰。 – unbeli 2010-06-07 15:35:28

+0

我認爲臨時變量是必要的,因爲OP正在對其執行操作,需要在構建後完成。 – 2010-06-07 15:35:35

0
Element tempElement; 

while(condition){ 
    tempElement = new HashElement(); 

    //do more stuff 

    elementArray[index] = tempElement; 
}