2013-03-10 77 views
-1

我一直在試圖解決過去一小時的java.lang.NullPointerException。當我調用play()方法並輸入no時會發生此錯誤。我已經評論錯誤指向下面的位置。我希望得到一些幫助。謝謝。爲什麼我得到java.lang.NullPointerException錯誤?

import java.util.ArrayList; 


public class Game 
{ 
private InputReader input ; 
private Deck newDeck; 
private ArrayList <Card> hand; 


public Game(Deck deckToAdd) 
{ 
    input = new InputReader(); 
    newDeck = deckToAdd; 
    hand = new ArrayList <Card>(); 
} 


public void dealCard() 
{ 

    hand.add(newDeck.takeCard()); 
} 

public void showHand() 
{ 
    for(Card showCards: hand){ 
     if(hand == null){ 
      System.out.println("(Warning, the deck may have been empty the last time you dealt a  card)"); 
     } 
      System.out.println(showCards.getDescription() + " of " + showCards.getSuit()); 
     // Error points to above line 
    } 
} 


public int getHandValue() 
{ 
    int counter = 0; 
    int handValue = 0; 
    while(counter < hand.size()){ 
     Card checker = hand.get(counter); 
     handValue += checker.getValue(); 
     counter++; 
    } 
    return handValue; 
} 

public void play()  //Error occurs when invoking this method and selecing no, points to showHand() method         
{ 
    boolean userWantsToPlay = true; 
    while(userWantsToPlay){ 
     dealCard(); 
     showHand(); 
     System.out.println("Hand Value : " + getHandValue()); 
     System.out.println("Do you want to continue? (yes or no)"); 
     String userInput = input.getInput(); 
     if(userInput == "no"){ 
      userWantsToPlay = false; 
     } 
    } 

} 
} 
+1

請儘量讓你的例子貼儘可能小。這將幫助我們幫助您調試問題。 – jontro 2013-03-10 10:55:28

+0

play()從哪裏調用?你可以顯示該代碼嗎? – angelatlarge 2013-03-10 10:57:03

回答

4

你的條件是錯誤的:

if (hand == null) { 
    // do your stuff 
} 
else { 
    // do your stuff 
} 

在你的情況,你的第二個System.out.println因爲不在狀態,這兩種情況下(NULL,NOT NULL)將被應用將一直執行。

注:此外,我看到你的代碼更「髒」的代碼,例如你是比較Strings==,它不會工作,因爲它比較的參考,而不是內容。始終當你想比較Strings你需要使用的equals()代替==所以

userInput.equals("no") { 
    // do your stuff 
} 
+0

感謝您的幫助 – 2013-03-10 11:12:25

+0

@JoshuaBaker歡迎您。 – Sajmon 2013-03-10 11:13:03

2

,而不是你的代碼:

for(Card showCards: hand){ 
     if(hand == null){ 
      System.out.println("(Warning, the deck may have been empty the last time you dealt a  card)"); 
     } 
      System.out.println(showCards.getDescription() + " of " + showCards.getSuit()); 
     // Error points to above line 
    } 

應該不會是

if(hand!=null){ 
for(Card showCards: hand){ 
     if(showCards== null){ 
      System.out.println("(Warning, the deck may have been empty the last time you dealt a  card)"); 
     }else{ 
      System.out.println(showCards.getDescription() + " of " + showCards.getSuit()); 

     } 
    } 
} 

檢查showCards代替hand.But調試將有幫助

3

你也應該更換:

userInput == "no" 

有了:

userInput.equals("no") 
相關問題