我一直在試圖解決過去一小時的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;
}
}
}
}
請儘量讓你的例子貼儘可能小。這將幫助我們幫助您調試問題。 – jontro 2013-03-10 10:55:28
play()從哪裏調用?你可以顯示該代碼嗎? – angelatlarge 2013-03-10 10:57:03