一段時間以來,我一直在研究一個將值散列到散列表中的程序(我不記得具體情況,具體細節本身與問題無關)。不管怎麼說,我有下面的代碼爲「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循環之外。
你最好了解Java編碼慣例:http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html。類名應以大寫字母開頭。 – 2010-06-07 15:31:28