0
我正在構造一個FrequencyBag,它將採用類似於整數,字符串或字符的形式,並且將採用數據並將其與其頻率配對。在LinkedList實現中我的方法的空指針異常
例如:
FrequencyBag<Integer> fb = new FrequencyBag<Integer>();
fb.add(cat);
fb.add(dog);
fb.add(horse);
fb.add(cat);
fb.add(cat);
將看起來像
(cat,3) ---> (dog,1) ---> (horse, 1)
我的方法getMaxFreq()沒有問題獲得最大頻率(它是3上面的例子),當所述袋包含的元素,但是當我嘗試返回空值null FrequencyBag()的值爲0時,出現此錯誤。
「異常線程 」main「 顯示java.lang.NullPointerException」 「FrequencyBag $ Node.access $ 1(FrequencyBag.java:8)」
這裏是我下面的方法:
public int getMaxFreq() {
Node<T> currentNode = firstNode;
Node<T> nextNode = firstNode.next;
int compareVal = nextNode.freq;
int maxVal = currentNode.freq;
if (currentNode == null) {
maxVal = 0;
return maxVal;
}
while (nextNode.next != null) {
if (maxVal < compareVal) {
maxVal = compareVal;
}
else {
// Do nothing
}
currentNode = currentNode.next;
nextNode = nextNode.next;
}
if (nextNode.next == null) {
if (maxVal < nextNode.freq) {
maxVal = nextNode.freq;
} else {
// Do nothing
}
return maxVal;
}
return maxVal;
}
非但沒有空指針錯誤的,我想這樣做,當我創建一個空袋子,叫我getMaxFreq()方法:
FrequencyBag<Integer> emptyBag = new FrequencyBag<Integer>();
System.out.println("Output: " + emptyBag.getMaxFreq());
Output: 0
什麼阻礙了你? – 2014-09-27 01:44:20
我不完全確定爲什麼我得到一個空指針異常。 – user3716274 2014-09-27 01:46:20
我的if(currentNode == null)語句應該已經處理了該錯誤,但仍然出現錯誤。 – user3716274 2014-09-27 01:46:51