簡體   English   中英

分配的空指針異常

[英]Null Pointer Exception for Assignment

所以我知道Null Point異常發生在哪里(Eclipse很有幫助)

我有以下課程:

/**
 * Card class - a typical playing card.
 * 
 * @author Colleen 
 * @version 2010.03.09
 */
public class Card
{
    private String suit;
    private int value;
    private String description;
    private static final String[] SUITS = {"Hearts", "Diamonds", "Spades", "Clubs"};
    private static final String[] DESCRIPTIONS = {
            "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
            "Jack", "Queen", "King"};

    public Card(){
        suit = "Spades";
        value = 0;
        description = "Joker";
    }

    public Card(String description, String suit){
        setSuit(suit);
        setValue(description);
        setDescription(description);
    }

    /**
     * @return the suit
     */
    public String getSuit() {
        return suit;
    }

    /**
     * @param suit the suit to set
     */
     public void setSuit(String suit) {
        int count = 0;
        boolean check = false;
        while(count < SUITS.length){
            if(suit == SUITS[count]){
                check = true;
            }
            count ++;
        }
        if(check == true){
            this.suit = suit;
        } else {
            suit = "Spades";
        }
     }

    /**
     * @return the value
     */
    public int getValue() {
        return value;
    }

    /**
    * @param value the value to set
    */
    public void setValue(String description) {
        if(description == "Two"){
            value = 2;
        } else if(description == "Three"){
            value = 3;
        } else if(description == "Four"){
            value = 4;
        } else if(description == "Five"){
            value = 5;
        } else if(description == "Six"){
            value = 6;
        } else if(description == "Sever"){
            value = 7;
        } else if(description == "Eight"){
            value = 8;
        }else if(description == "Nine"){
            value = 9;
        } else if(description == "Ten" || description == "Jack" || description == "Queen" ||  description == "King"){
            value = 10;
        } else if(description == "Ace"){
            value = 11;
        } else {
            description = "Joker";
            value = 0;
        }
    }

    /**
     * @return the description
     */
    public String getDescription() {
        return description;
    }

    /**
     * @param description the description to set
     */
    public void setDescription(String description) {
        int count = 0;
        boolean check = false;
        while(count < DESCRIPTIONS.length){
            if(description == DESCRIPTIONS[count]){
                check = true;
            } 
            count ++;
        }
        if(check == true){
            this.description = description;
        } else {
            description = "Joker";
        }
     }
 }

下一課:

 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Random;

 /**
  * Deck of cards.
  * 
  * @author Bullwinkle J. Moose
  * @version (June 11, 2012)
  */
 public class Deck
 {
     private ArrayList<Card> deck;
     private static final int TIMES_TO_SHUFFLE = 5;
     private static final String[] SUITS = {"Hearts", "Diamonds", "Spades", "Clubs"};
     private static final String[] DESCRIPTIONS = {
             "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
             "Jack", "Queen", "King"};

     /**
      * Constructor for objects of class Deck
      * Creates a new container for Card objects
      */
     public Deck()
     {
         deck = new ArrayList<Card>();
     }

     /**
      * Add a card to the deck.
      * @param Card to be added
      */
     public void addCard(Card cardToAdd)
     {
         deck.add(cardToAdd);
     }

     /**
      * Take the first card from the deck.
      * @return Card or null
      */
     public Card takeCard()
     {
         if(deck.isEmpty()) {
             return null; 
         }
         else {  // get the top card
            return deck.remove(0);
         }
     }

     public int deckSize(){
        int deckSize = deck.size();
        return deckSize;
     }

     /**
      * Show the contents of the deck.
      */
     public void showDeck(){
         for(Card eachCard : deck) {
             System.out.println(eachCard.getDescription() + " of " + eachCard.getSuit());
         }
     }

     /**
      * Method that switch the index position in the deck of the two cards.
      */
     public void swap(int firstNumber, int secondNumber){        
         if (firstNumber >= 0 && firstNumber < deck.size()) {
             if (secondNumber >= 0 && secondNumber < deck.size()) {
                 Collections.swap(deck,firstNumber,secondNumber);
             } else {
                 System.out.println("Invalid index entry ...");
             }
         } else {
             System.out.println("Invalid index entry ...");
         }
     }

     /**
     * Method that randomly selects two numbers between 0 (inclusive) and the size of the deck (exclusive),
      * and passes those numbers as parameters to swap(). This must be within a loop, so that the 
      * swap() method is called TIMES_TO_SHUFFLE times.
      */    
     public void shuffle(){
         Random randomGenerator = new Random();
         int counter = 0;
         int firstNumber, secondNumber = 0;
         while (counter++ < TIMES_TO_SHUFFLE){
             firstNumber = randomGenerator.nextInt(deck.size());
             secondNumber = randomGenerator.nextInt(deck.size());
             swap(firstNumber,secondNumber);
        }    
     }

     public void loadDeck() {
         for (int suit = 0; suit < SUITS.length; suit++) {
             for (int description = 0; description < DESCRIPTIONS.length; description++) {
                 Card card = new Card(DESCRIPTIONS[description], SUITS[suit]);
                 deck.add(card);
             }
         }
     }
 }

最后一堂課:

 import java.util.ArrayList;

 /**
  * @author jaimefenton
  *
  */
 public class Game {

     private Deck aDeck;
     private InputReader reader;
     private ArrayList<Card> hand;
     private String commandChoice;

     /**
      * Method to run the game. 
      * First while loop will run until the player chooses "no" for another round.
      * Second while look will keep running until the player chooses to stand, has 21 or busts.
      * the last while loop is to make sure that the player chooses either "Hit" or "Stand". If neither is choosen, it will keep requesting it.
      */
     public void Play(){
        int playerPoints = 0;
        int totalRounds = 0;

        intro();
        aDeck = new Deck();
        aDeck.loadDeck();
        while(anotherRound() == false){
            dealCard();
            dealCard();
            showHand();
            report();
            while(isStanding() == false){
                if(hasBlackjack() == true){
                        hasBlackjack();
                System.out.println("BlackJack!");
                }else if (isBusted() == true){
                    isBusted();
                    System.out.println("You have Busted!");
                }else {
                    dealCard();
                    report();
                    System.out.println("Your choice: Hit or Stand? ");
                    String inputChoice = reader.getInput();
                    while(inputChoice != "Hit" || inputChoice != "Stand"){
                        System.out.println("That is not a correct choice.");
                    }
                    isStanding();
                }

         } totalRounds ++;
        }
        System.out.println("Player Points: " + playerPoints);
         System.out.println("Total Rounds: " + totalRounds);
     }

     /**
      * intro message to player
      */
     public void intro(){
        System.out.println("Welcome to 1451 Blackjack!");
        System.out.println("You will start with two cards.");
        System.out.println("You will be prompted to 'hit' or 'stand' 'hit' means you want another card, 'stand' not.");
        System.out.println("");
        System.out.println("You are trying to get Blackjack with exactly 21 points.");

     }
     /**
      * deals a card to the player
      */
     public void dealCard(){
        int deckSize = aDeck.deckSize();
        if(deckSize == 0){
            System.out.println("Time for some more cards");
            aDeck.loadDeck();
            aDeck.shuffle();
         } else {
         Card tempCard = aDeck.takeCard();
         hand.add(tempCard);
         }
     }

     /**
      * calculates the hand value of the player
      * @return handValue
      */
     public int getHandValue(){
        int handValue = 0;
        for(Card eachCard : hand) {
             int tempValue = eachCard.getValue();
             handValue = handValue + tempValue;
         }
        return handValue;
     }

     /**
      * displays contents of players hand
      */
    public void showHand(){
        System.out.println("Your cards:"); 
         for(Card eachCard : hand) {
                 System.out.println(eachCard.getDescription()+ 
                                 " of " + eachCard.getSuit());
             }
     }

     /**
      * displays contents of hand
      * @return true or false
      */
    public boolean hasBlackjack(){
        int bjValue = getHandValue(); 
        if(bjValue == 21){
            return true;
        } else {
            return false;
        }
     }

     /**
      * is hand value above 21?
      */

     public boolean isBusted(){
        int bjValue = getHandValue(); 
        if(bjValue > 21){
            return true;
         } else {
            return false;
         }
     }

     /**
      * has player chosen to "stand"?
      * @return true or false
      */
     public boolean isStanding(){
        if(commandChoice == "Hit"){
            return true;
        } else {
            return false;
        }
     }

     public boolean anotherRound(){
        if(commandChoice == "no"){
            return true;
        } else {
            return false;
        }
     }

     /**
      * final report of points
      */
     public void report(){
        showHand();
        System.out.println("Hand Value: " + getHandValue());
        System.out.println(""); 
     }
 }

我沒有包含InputReader,因為它對這個問題並不重要。

我使用的驅動程序類已對DeckCard進行了全面測試,並且均返回了肯定的結果。 請記住,我知道play()可能被搞砸了,但是直到我解決了它所調用的方法之前,我將無法修復它。

我遇到的第一個錯誤是“ public void dealCard() ”。 它正在拉出與“ if(deckSize == 0) ”有關的零點異常錯誤。 我不知道為什么它不起作用,因為當我直接從平台運行它時,它可以完美地工作。 一旦問題解決,我就可以確定其余的工作。

感謝您對此進行檢查。

我很確定hand是空的。 reader也可以為null。 我看不到他們分配了任何東西(諸如hand =reader =的表達式),並且它們是私有的。

這就是為什么您應該初始化成員變量或使用構造函數的原因,除非出於某些原因您不能這樣做:

public class Game {

    private Deck aDeck = new Deck();
    private InputReader reader = /* ??? */;
    private ArrayList<Card> hand = new ArrayList<Card>();

    private String commandChoice;

    /*
     */

通常,對象成員的生存期應與對象相同,換句話說,您應始終在創建對象時實例化一次成員。 以可能多次調用的Play方法進行操作,會增加對象最終處於某種無效狀態的可能性。 (或者在這種情況下,以無效狀態開始。)

我還注意到您正在這樣做:

String inputChoice = reader.getInput();
while(inputChoice != "Hit" || inputChoice != "Stand"){

幾乎可以肯定是不正確的

您永遠不會初始化hand ,它是Game類的成員變量。

必須先初始化ArrayList,然后才能調用它們的方法。

dealCard()的以下行將始終拋出NullPointerException

  hand.add(tempCard);

修改聲明的行,如下所示:

  private ArrayList<Card> hand = new ArrayList<Card>();

正如Radiodef所提到的,使用標准構造函數會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM