分配的空指针异常

时间:2014-10-14 02:13:53

标签: java nullpointerexception

所以我知道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()可能搞砸了,但在我解决它调用的方法之前,我无法修复它。

我遇到的第一个错误是&#34; public void dealCard()&#34;。它会提取与&#34; if(deckSize == 0)&#34;相关的零点异常错误。我不能告诉它为什么不能正常工作,因为当我直接从甲板上运行时,它完美无缺。一旦问题得到解决,我相当肯定我可以解决剩下的问题了。

感谢您查看此内容。

2 个答案:

答案 0 :(得分:1)

我很确定hand为空。 reader也可能为空。我没有看到他们分配任何内容(类似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"){

这是almost certainly incorrect

答案 1 :(得分:0)

您永远不会初始化 hand ,这是 Game 类的成员变量。

必须先初始化

ArrayLists ,然后才能调用它们的方法。

dealCard()的以下行将始终抛出 NullPointerException

  hand.add(tempCard);

修改声明 hand 的行如下所示:

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

正如Radiodef所提到的,使用标准构造函数会更好。