2014-12-02 136 views
-2

每當我調用pennyCount方法或removePenny方法,我得到一個空指針異常錯誤,我不明白,因爲我的HashSet應該填充在構造函數中。爲什麼我得到這個,我該如何解決它?爲什麼我收到java.lang.NullPointerException錯誤

import java.util.HashSet; 

public class Pocket 
{ 

private HashSet<Penny> penniesSet; 



public Pocket(int numOfPennies){ 

    HashSet<Penny> penniesSet = new HashSet<Penny>(); 

    for(int n = 0; n < numOfPennies; n++){ 
     penniesSet.add(new Penny());} 



} 

public int pennyCount(){ 
    return penniesSet.size(); 

} 

public Penny removePenny(){ 

    if(penniesSet.size() == 0){ 
     return null; 
    } 
    else{ 
     Penny toRemove = penniesSet.iterator().next(); 
     penniesSet.remove(toRemove); 
     return toRemove; 

    } 
} 

}

+0

東西是空的。所以你得到NullPointerException。:) – subash 2014-12-02 14:59:26

回答

0

在構造函數中,你有以下

HashSet<Penny> penniesSet = new HashSet<Penny>(); 

應該

penniesSet = new HashSet<Penny>(); 
0

在你的構造你宣佈一個新的HashSet penniesSet,它應該是:

public Pocket(int numOfPennies){ 

     penniesSet = new HashSet<Penny>(); 

     for(int n = 0; n < numOfPennies; n++){ 
      penniesSet.add(new Penny());} 
} 

否則你是pennieSet永遠不會初始化。

0

嘗試

public Pocket(int numOfPennies){ 

    penniesSet = new HashSet<Penny>(); // was HashSet<Penny> penniesSet = new HashSet<Penny>(); 

    for(int n = 0; n < numOfPennies; n++){ 
     penniesSet.add(new Penny());} 



} 
+0

你的答案看起來不錯,但你可以添加一個解釋如何解決OP問題? – thegrinner 2014-12-02 15:38:45

+0

我的答案是每個人都在一起,有什麼問題? – outdev 2014-12-02 15:57:54

+0

他們大多數都會詳細討論爲什麼改變這條線可以修復它(也就是說,當OP重新聲明它時,該變量是被遮蔽的)。我評論你的答案,因爲我在評論隊列中看到它(因爲它主要是代碼)。只是一個FYI :) – thegrinner 2014-12-02 16:00:50

0

改變這樣的。

public Pocket(int numOfPennies){ 

    penniesSet = new HashSet<Penny>(); 

    for(int n = 0; n < numOfPennies; n++){ 
     penniesSet.add(new Penny());} 

} 
+1

這將是很好,如果你解釋,OP的問題是什麼,以及如何解決它在這裏。 – blalasaadri 2014-12-02 15:27:21

0

變化

public Pocket(int numOfPennies){ 

    HashSet<Penny> penniesSet = new HashSet<Penny>(); 

    for(int n = 0; n < numOfPennies; n++){ 
     penniesSet.add(new Penny());} 



} 

public Pocket(int numOfPennies){ 

    penniesSet = new HashSet<Penny>(); //set the instance variable instead of creating a local variable 

    for(int n = 0; n < numOfPennies; n++){ 
     penniesSet.add(new Penny());} 



} 
0

您在構造函數中創建一套新的對象,而不是填充類的領域。嘗試:

penniesSet = new HashSet<Penny>(); 
1

您在構造函數中創建兩個具有相同名稱的字段和一個本地HashSet。會發生什麼是局部變量將被實例化。到達pennyCount()時,該字段仍然爲空。

private HashSet<Penny> penniesSet; //first here 

public Pocket(int numOfPennies){ 
    HashSet<Penny> penniesSet = new HashSet<Penny>(); //then here 

要更正這樣做。

private HashSet<Penny> penniesSet; 

public Pocket(int numOfPennies){ 
    penniesSet = new HashSet<Penny>(); 
相關問題