2014-09-27 61 views
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 
+1

什么阻碍了你? – 2014-09-27 01:44:20

+0

我不完全确定为什么我得到一个空指针异常。 – user3716274 2014-09-27 01:46:20

+0

我的if(currentNode == null)语句应该已经处理了该错误,但仍然出现错误。 – user3716274 2014-09-27 01:46:51

回答

0

你可能想尝试先检查currentNode == NULL,然后尝试对第7行上的currentNode进行解引用(看起来),这行 - > int maxVal = currentNode.freq;

否则你试图取消引用空指针是是是喜欢扔的是NullPointerException异常

这同样适用于“nextNode”