开发者

confused with NullPointerexception error in my blackjack card program

I am making a black jack card game. I am confused about the error that my program is having. Any help would be highly appreciated. Thanks in advance!

This is the error that I get when I run my code:

Exception in thread "main" java.lang.NullPointerException at BlackJackCardGame.DealHands(BlackJackCardGame.java:197) at BlackJackCardGame.PlayBlackJack(BlackJackCardGame.java:207) at BlackJackCardGame.main(BlackJackCardGame.java:252)

My code is below:

 import java.util.Scanner;
//import java.util.*;
public class BlackJackCardGame 
{
static class Player
{
    private String Name;
    private int handValue;
    private boolean BlackJack;
    private TheCard[] Hand;
    public Player(String name)
    {
        this.Name = name;
        this.handValue = 0;
        this.BlackJack = false;
        this.Hand = null;
    } 
}
private static Player[] InitializePlayers(int PlayerCount)
{
    Player[] thePlayers = new Player[PlayerCount + 1];
    for(int i = 0; i < PlayerCount + 1; i++)
    {
        String tempName;
        if (i == 0)
        {
            tempName = "Dealer"; 
        }
        else
        {
            tempName = "Player_" + String.valueOf(i);
        }
        thePlayers[i] = new Player(tempName);
    }
    return thePlayers;
}

static class TheCard
{
    // Java getter & setter
    private String CardName;
    private int CardRank;
    private int Chosen;

    public TheCard(int rank, String name)
    {
        this.CardName = name;
        this.CardRank = rank;
        this.Chosen = 0;
    }
}

private static TheCard[] BuildDeck(int decks)   
{
    String[] Cards = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
    String[] Suits = {"Spades","Hearts","Diamonds","Clubs"};
    TheCard[] theDeck = new TheCard[Cards.length * Suits.length];
    //int String [] = {2,3,4,5,6,7,8,9,10,11,12,13,14};
    int[] Rank = {2,3,4,5,6,7,8,9,10,10,10,10,11};
    int cardnumber = 0;
    for (int d = 0; d < decks; d++)
    {
        for (int i = 0; i < Cards.length; i++)
        {
            for (int j = 0; j < Suits.length; j++)
            {
                String deckcard = Cards[i];
                String suitcard = Suits[j];
                String cardname = deckcard + "-" + suitcard;
                theDeck[cardnumber] = new TheCard(Rank[i], cardname);  
                cardnumber++;
            }
        }
    }   
    return theDeck;
}

private static TheCard Deal(TheCard[] OrderedDeck) 
{   // this method uses Random method to "deal" a single card from the playing deck
    TheCard thecard;
    int NumberofCards = OrderedDeck.length;
    int random = (int) (NumberofCards*Math.random ());
    thecard = OrderedDeck[random];
    if (thecard.Chosen == 0 )       // if available... 
    {
        thecard.Chosen = 1;         // mark it taken...
        return thecard;
    }
    else
    {
        return Deal(OrderedDeck);
    }
}
private static int ShowCardOfDealer(Player player, int cardNumber)
{
    System.out.println (player.Name + ", is holding a: ");
    System.out.println (player.Hand[cardNumber].CardName);
    int value = player.Hand[cardNumber].CardRank;
    System.out.println ("..with value of: " + String.valueOf(value));
    return value;
}
private static void DealerPlays(TheCard[] deck,Player[] players)
{
    Player currentPlayer = players[0];     // dealer first in array
    int handValue = ShowHand(currentPlayer);
    int choice = 1;
        do
        {
            if (handValue < 17 )
            {
                TheCard newCard = Deal(deck);
                int numCards = currentPlayer.Hand.length;
                currentPlayer.Hand[numCards + 1] = newCard;
                handValue = ShowHand(currentPlayer);
                if (handValue > 21) 
                {
                    System.out.println ("The Dealer has busted!");
                    handValue = 0;  // special signal that this value always loses
                    choice = 0;     
                }
            }
            else
            {
                System.out.println ("The Dealer stays.");
                choice = 0;  //dealer is forced to stay, =>17
            }

        } while ( choice == 1);
}
private static void MakeChoices(TheCard[] deck,Player[] players)
{
    for( int i = 1; i < players.length -1 ; i++ )
    {
        Player currentPlayer = players[i];
        int handValue = ShowHand(currentPlayer);
        Scanner input = new Scanner(System.in);
        int choice = 0;
        do
        {
            System.out.println ("Make your choice please. Type 1 for Hit or type 0 for Stay.");
            choice = input.nextInt();
            if (choice == 1) 
            {
                // DealAnotherCardToPlayerX
                // what player is going to be updated
                // add new card to players hand
                TheCard newCard = Deal(deck);
                int numCards = currentPlayer.Hand.length;
                currentPlayer.Hand[numCards + 1] = newCard;
                handValue = ShowHand(currentPlayer);
                if (handValue > 21) 
                {
                    System.out.println ("You have busted!");
                    handValue = 0;  // special signal that this value always loses
                    choice = 0;     //this guy is done, loop to next player
                }
            }
        } while ( choice == 1);
        currentPlayer.handValue = handValue;
    }
}
private static void setBlackJackCase(Player player)
{
    player.BlackJack = false;
    if (player.Hand[0].CardRank == 10 && player.Hand[1].CardRank == 11) 
    {
        player.BlackJack = true;
    }
    if (player.Hand[1].CardRank == 10 && player.Hand[0].CardRank == 11) 
    {
        player.BlackJack = true;
    }
}
private static int ShowHand(Player player)
{
    int cards = player.Hand.length;     // get number of cards player x has
    System.out.println (player.Name + ", you are holding: ");
    int value = 0;
    for (int c = 0; c < cards; c++ )
    {
        System.out.println (player.Hand[c].CardName);
        //value = value + player.Hand[c].CardRank;
        value += player.Hand[c].CardRank;
    }
    setBlackJackCase(player);
    System.out.println ("Your total card value is: " + String.valueOf(value));
    return value;
}
private static void DealHands(TheCard[] deck,Player[] players)
{
    for (int c = 0; c < 2; c++)
    {
        for( int i = 1; i < players.length -1 ; i++ )
        {
            TheCard card = Deal(deck);
            players[i].Hand[c] = new TheCard(card.CardRank, card.CardName);
        }
        //give dealer card
        The开发者_StackOverflow中文版Card card = Deal(deck);
        players[0].Hand[c] = new TheCard(card.CardRank, card.CardName);
    }
}
private static void PlayBlackJack(TheCard[] playingDeck, Player[] players)
{

    DealHands( playingDeck, players);    // everybody has their hands - ready for choices:
    ShowCardOfDealer ( players[0], 0);  //shows dealer's turned up card
    MakeChoices (playingDeck, players);  // everybody is either out or at "stay"
    DealerPlays (playingDeck, players);  // Dealer "plays" and Dealer Rules
    AnnounceWinners (players);
}
private static void AnnounceWinners(Player[] players)
{
    int dealerHand = players[0].handValue;
    for( int i = 1; i < players.length -1 ; i++ )
    {
        int playerHand = players[i].handValue;
        if (players[i].BlackJack) 
        {
                System.out.println (players[i].Name + ", you have BlackJack! :) You WIN!");
        }
        else
        {
            if (dealerHand == 0 && playerHand == 0)
            {
                System.out.println (players[i].Name + " has busted..");
            }
            if (dealerHand >= playerHand )
            {
                System.out.println ("Dealer wins" );
            }
            else
            {
                System.out.println (players[i].Name + ", you WIN!");
            }
        }
    }   
}
public static void main(String args[])
{

    System.out.println ("Welcome, to the game of Black Jack");
    Scanner input = new Scanner(System.in);
    System.out.println ("How many decks of cards are in this game? Enter a number from 1 to 3.");
    int decks = input.nextInt();
    System.out.println ("How many players are in this game? (Not counting the Dealer)");
    int numPlayers = input.nextInt();
    TheCard[] PlayingDeck = BuildDeck(decks);
    Player[] thePlayers = InitializePlayers(numPlayers);
    //loop 
        PlayBlackJack(PlayingDeck, thePlayers);
        System.out.println ("Play Again? Type 'y' or 'n'");
    //test answer
}
}


You haven't given enough information to easily point out the problem, but you have all the information you need since you can see the line numbers. Find line 197 and look at every object on that line. One of them is null and you're trying to treat it as if it were a valid object.

private static void DealHands(TheCard[] deck,Player[] players)
{
    for (int c = 0; c < 2; c++)
    {
        for( int i = 1; i < players.length -1 ; i++ )
        {
            TheCard card = Deal(deck);
            players[i].Hand[c] = new TheCard(card.CardRank, card.CardName);
        }
        //give dealer card
        TheCard card = Deal(deck);
        players[0].Hand[c] = new TheCard(card.CardRank, card.CardName);
    }
}

My guess is you haven't initialized the player's Hand in your Player constructor, so players[i].Hand[c] tries to access an index in a null array. You need to initialize the array to some length, first.


Note this line of code in the Player constructor: this.Hand = null; .


You are not initialising the Player.Hand array correctly

in your Player class constructor(line 16) you set

this.Hand = null;

And in your method

private static Player[] InitializePlayers(int PlayerCount)

on line 19, you do not update this, so on line 196 (the nullpointer) when you try to do the following:

players[i].Hand[c] = new TheCard(card.CardRank, card.CardName);

players[i].Hand[] is null, so you get your error. Make sure in the InitializePlayer method you set the Hand to a non-null array.

(As an aside, normal Java convention is lower camel case for method and class member names e.g. variables such as "Hand" should be "hand" and methods "InitializePlayer" should be like "initializePlayer")


public Player(String name) {
        this.Name = name;
        this.handValue = 0;
        this.BlackJack = false;
        this.Hand = null;
}

check the line this.Hand = null; and then you used Hand at :

private static void DealHands(TheCard[] deck, Player[] players) {
    for (int c = 0; c < 2; c++) {
        for (int i = 1; i < players.length - 1; i++) {
            TheCard card = Deal(deck);
            players[i].Hand[c] = new TheCard(card.CardRank, card.CardName);
        }
        // give dealer card
        TheCard card = Deal(deck);
        System.out.print("Card == null" + card == null);

        players[0].Hand[c] = new TheCard(card.CardRank, card.CardName);
    }

}

Here In the line: players[0].Hand[c] = new TheCard(card.CardRank, card.CardName);

So try to declare this.Hand = new TheCard[2]; //here 2 is just for an example

And then, you have another problem in your code

private static void DealerPlays(TheCard[] deck, Player[] players) {
    Player currentPlayer = players[0]; // dealer first in array
    int handValue = ShowHand(currentPlayer);
    int choice = 1;
    do {
        if (handValue < 17) {
            TheCard newCard = Deal(deck);
            int numCards = currentPlayer.Hand.length;
            currentPlayer.Hand[numCards + 1] = newCard;
            handValue = ShowHand(currentPlayer);
            if (handValue > 21) {
                System.out.println("The Dealer has busted!");
                handValue = 0; // special signal that this value always
                                // loses
                choice = 0;
            }
        } else {
            System.out.println("The Dealer stays.");
            choice = 0; // dealer is forced to stay, =>17
        }

    } while (choice == 1);
}

Check the lines below and Fix it, this is a sure exception of type "ArrayIndexOutOfBoundsException".

int numCards = currentPlayer.Hand.length;
currentPlayer.Hand[numCards + 1] = newCard;


The top of your stack trace references line 197. Unless your source snippet is missing lines, line 197 is this:

players[i].Hand[c] = new TheCard(card.CardRank, card.CardName);

Any time you access an object using the dot operator ., a NPE will be thrown if the object being accessed is null. A NPE can also be thrown when attempting to index into an array variable whose reference is null. So the suspects are:

players
players[i]
players[i].Hand
card

One of the above must be null. I suggest using a debugger to break at line 197 and inspect each of the suspect. Once you find which one is the culprit, you can then work backward and try to figure out how it became null in the first place.

(Note that card.CardRank and card.CardName are not included above; that is because if they were the problem your exception would have been thrown from within the constructor for TheCard.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜