2013-03-10 56 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") 
相关问题