-1

過去 1 時間、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;
        }
    }

}
}
4

3 に答える 3

4

あなたの状態は間違っています:

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

あなたの場合、2番目System.out.printlnは常に実行されます。これは、が状態になく、両方の場合(null、not null)が適用されるためです。

注:Stringsまた、あなたのコードには、たとえば比較している「汚れた」コードが表示されますが==、コンテンツではなく参照を比較するため、機能しません。比較したいときは常にsoの代わりにStrings使用する必要がありますequals()==

userInput.equals("no") {
   // do your stuff
}
于 2013-03-10T10:54:28.573 に答える
3

以下も置き換える必要があります。

userInput == "no"

と:

userInput.equals("no")
于 2013-03-10T11:01:09.443 に答える
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をチェックしていますが、デバッグが役に立ちました

于 2013-03-10T10:56:34.147 に答える