为什么我收到java.lang.NullPointerException错误?

时间:2013-03-10 10:52:58

标签: java

我一直在尝试解决过去一小时的java.lang.NullPointerException。当我调用play()方法并输入no时,会发生此错误。我已经评论了错误指向下面的位置。我将不胜感激。感谢。

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;
        }
    }

}
}

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:3)

您还应该替换:

userInput == "no"

使用:

userInput.equals("no")

答案 2 :(得分: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 Debugging会帮助