I made a poker game and when I run it I get these errors...

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at PokerGame.Hand.getPairs(Hand.java:82)
        at PokerGame.Hand.whichHand(Hand.java:28)
        at PokerGame.DeckOfCards$1.actionPerformed(DeckOfCards.java:67)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:6263)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
        at java.awt.Component.processEvent(Component.java:6028)
        at java.awt.Container.processEvent(Container.java:2041)
        at java.awt.Component.dispatchEventImpl(Component.java:4630)
        at java.awt.Container.dispatchEventImpl(Container.java:2099)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
        at java.awt.Container.dispatchEventImpl(Container.java:2085)
        at java.awt.Window.dispatchEventImpl(Window.java:2475)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

bbcode

Here is my code

package PokerGame;


public class Card
{
    private String face;
    private String suit;

    public Card(String cardFace, String cardSuit)
    {
        face = cardFace;
        suit = cardSuit;
    }

    public Card(Card c)
    {
        face = c.face;
        suit = c.suit;
    }

    @Override
    public String toString()
    {
        return face + " of " + suit;
    }


    public String getFace()
    {
        return face;
    }

    public String getSuit()
    {
        return suit;
    }

    public int value(){
        int result = 0;

        if (face.equals("Ace"))
            result = 1;
        if (face.equals("Deuce"))
            result = 2;
        if (face.equals("Three"))
            result = 3;
        if (face.equals("Four"))
            result = 4;
        if (face.equals("Five"))
            result = 5;
        if (face.equals("Six"))
            result = 6;
        if (face.equals("Seven"))
            result = 7;
        if (face.equals("Eight"))
            result = 8;
        if (face.equals( "Nine"))
            result = 9;
        if (face.equals("Ten"))
            result = 10;
        if (face.equals("Jack"))
            result = 11;
        if (face.equals("Queen"))
            result = 12;
        if (face.equals("King"))
            result = 13;

        return result;

    }


}

bbcode

public class Hand {

    private Card[] cards;
    private int size;
    private int pairs;
    private int kind;
    private int score;


    public Hand(){

    size = 0;
    cards = new Card[5];
    pairs = 0;
    kind = 0;
    score = 0;
}

    public int getScore(){
        return score;
    }

    public String whichHand(){
        String x = "";
        int p = getPairs(), k = getKind();

        if(p==1 || p==2){
            x=("" + p + " pair(s)");
            if(p==1){
                score = 1;
            }
            else
                score = 2;
        }

        if(k==3 || k==4){
            x=("" + k + " of a kind");
            if(k==3){
                score = 3;
            }
            else
                score = 4;
        }

        if(isFlush() == true){
            x = "Flush";
            score = 5;
        }

        if(isStraight() == true){
            x = "Straight";
            score = 6;
        }

        if(isFullHouse() == true){
            x = "Full House";
            score = 7;
        }

        if(isStraightFlush() == true){
            x = "Straight Flush";
            score = 8;
        }

        return x;
    }

    
    public void addCard(Card c){
        cards[size] = c;
        size++;
    }

    private int getPairs(){
        for (int i=0; i<cards.length; i++){

            for (int j=0; j<cards.length; j++){

                if (cards[i].getFace().equals(cards[j].getFace()) && j != i){
                    pairs++;
                }
            }
        }
        return pairs/2;
    }

    private int getKind(){
        for (int i=0; i<cards.length; i++){

            for (int j=0; j<cards.length; j++){

                if (cards[i].getFace().equals(cards[j].getFace()) && j != i){
                    kind++;
                }
            }
        }

        if (kind %4 == 0){
            return (kind/3);
        }

        if (kind %3 == 0){
            return (kind/2);
        }
        else{
            return 0;
        }
    }

    private boolean isFlush(){
        String testSuit = cards[0].getSuit();

        for (int i=0; i<cards.length; i++){

            if (cards[i].getSuit().equals(testSuit)){
                return true;
            }
        }
        return false;
    }

    private boolean isStraight(){
        int min = 0;

        for (int i=0; i<cards.length; i++){
            min = i;
            int j;
            for(j = (i+1); j<cards.length; j++){

                if (cards[j].value() < cards[min].value()){
                    min = j;
                }
            }
        }

        min = cards[min].value();

        for(int x=0; x<cards.length; x++){

            if (search(min - x) == false){
                return false;
            }
        }
        return true;
    }

    public boolean search(int s, int index){
        for (int i=0; i<cards.length; i++){

            if (cards[i].value() == s){

                if(i == index){
                    i++;
                }
                else{
                    return true;
                }
            }
        }
        return false;
    }

    public boolean search(int s){
        for(int i=0; i<cards.length; i++){

            if (cards[i].value() == s){
                return true;
            }
        }
        return false;
    }

    private boolean isFullHouse(){
        if (pairs == 4 && kind == 3){
            return true;
        }
        return false;
    }

    private boolean isStraightFlush(){
        if (isStraight() == true && isFlush() == true){
            return true;
        }
        return false;
    }

}

bbcode

import java.util.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;

public class DeckOfCards extends JFrame {

    private Card[] deck;
    private int currentCard;
    private static final int NUMBER_OF_CARDS = 52;
    private static final Random randomNumbers = new Random();
    private JButton dealButton, shuffleButton;
    private JTextField displayField1, displayField2, compare;
    private JLabel statusLabel;
    private JTextField[] player1;
    private JTextField[] player2;

    public DeckOfCards() {
        super("2 Player Poker");
        String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
            "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
        String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};

        deck = new Card[NUMBER_OF_CARDS];

        player1 = new JTextField[5];
        player2 = new JTextField[5];

        for (int x = 0; x < player1.length; x++) {
            player1[x] = new JTextField(20);
            player2[x] = new JTextField(20);
        }

        compare = new JTextField(10);

        currentCard = 0;
        for (int count = 0; count < deck.length; count++) {
            deck[count] = new Card(faces[count % 13], suits[count / 13]);
        }

        Container container = getContentPane();
        container.setLayout(new FlowLayout());

        dealButton = new JButton("Deal");
        dealButton.addActionListener(
                new ActionListener() {

                    public void actionPerformed(ActionEvent actionEvent) {

                        Hand hand1 = new Hand();
                        Hand hand2 = new Hand();

                        for (int i = 0; i < player1.length; i++) {
                            Card dealt = dealCard();

                            if (dealt != null) {
                                player1[i].setText(dealt.toString());
                                hand1.addCard(dealt);
                            } else {
                                displayField1.setText("No More Cards to Deal.");
                                displayField2.setText("Shuffle to continue.");
                            }
                        }
                        displayField1.setText(hand1.whichHand());

                        for (int j = 0; j < player2.length; j++) {
                            Card dealt = dealCard();

                            if (dealt != null) {
                                player2[j].setText(dealt.toString());
                                hand2.addCard(dealt);
                            } else {
                                displayField1.setText("No More Cards to Deal.");
                                displayField2.setText("Shuffle to continue.");
                            }
                        }
                        displayField2.setText(hand2.whichHand());

                        int score1 = hand1.getScore();
                        int score2 = hand2.getScore();

                        if (score1 > score2) {
                            compare.setText("Player 1 Wins!!!");
                        }

                        if (score1 > score2) {
                            compare.setText("Player 2 Wins!!!");
                        }

                        if (score1 == score2) {
                            compare.setText("Tie!!!");
                            
                        }
                    }
                }
        );
        
        container.add(dealButton);
        
        shuffleButton = new JButton("Shuffle Deck");
            shuffleButton.addActionListener(
               
                    new ActionListener(){
                public void actionPerformed(ActionEvent actionEvent){
                    
                    shuffle();
                    displayField1.setText("Deck has been shuffled.");
                    displayField2.setText("Deck has been shuffled.");
                }
            }
    );
    
    container.add(shuffleButton);
    
    displayField1 = new JTextField(20);
    displayField1.setEditable(false);
    container.add(displayField1);
    
    int x;
    for (x=0; x<player1.length; x++){
        container.add(player1[x]);
    }
    
    displayField2 = new JTextField(20);
    displayField2.setEditable(false);
    container.add(displayField2);

    for (x=0; x<player2.length; x++){
        container.add(player2[x]);
    }

        container.add(compare);
        compare.setEditable(false);

        setSize(275, 400);
        show();
    }

    public void shuffle() {
        currentCard = 0;

        for (int first = 0; first < deck.length; first++) {
            int second = randomNumbers.nextInt(NUMBER_OF_CARDS);

            Card temp = deck[first];
            deck[first] = deck[second];
            deck[second] = temp;

        }
        dealButton.setEnabled(true);

    }

    public Card dealCard() {
        if (++currentCard < deck.length) {
            return deck[currentCard];
        } else {

            dealButton.setEnabled(false);
            return null;
        }
    }

}

bbcode

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


public class DeckOfCardsTest
{


    public static void main(String[] args)
    {
        DeckOfCards app = new DeckOfCards();
        app.addWindowListener(
                new WindowAdapter(){
            public void windowClosing(WindowEvent windowEvent){
                System.exit(0);
            }
        }

     );

    }
}

bbcode

Where am I going wrong?

Recommended Answers

All 4 Replies

As the error mentions you are getting a null pointer exception when trying to get the face of the card.

I ran this program in debug mode and in the getPairs() method this is what i found:

cards (array) = [Seven of Spades, null, null, null, null]
i = 0
j = 1

The NPE occurs when trying to access the 2nd position of the array (j).

Hopefully this can shed some light on why the error was caused.

Let me know what you have tried to do to solve this and I can offer further assistance.

Cheers

I see that there is only one thing in the array and that is why the error is being thrown. However, I still can't see why there are not 5 cards in the array. Can you please give me a hint where to look to see why the other four cards are not being added?

I see that there is only one thing in the array and that is why the error is being thrown. However, I still can't see why there are not 5 cards in the array. Can you please give me a hint where to look to see why the other four cards are not being added?

The problem occurs when you go into the dealCard() method. Each time you call it you increment the current card by 1. This is done 5 times per player (10 times in total). The error occurs when you press it for the 6th time in which you are trying to get a position higher than the array therefore filling up the card array with null's. Later you are accessing the card array and receive the npe.

You should put a check in the deal card method in which you do something like:

public Card dealCard() {
        if (++currentCard < deck.length) {
            //check to see if the next couple queries are enough to cause a npe
            //where this is called from
            if(currentCard + 10 > deck.length)  dealButton.setEnabled(false);
                        
            return deck[currentCard];
        } else {
            
            dealButton.setEnabled(false);
            return null;
        }
    }

The null is then

Thanks. That got rid of the error, but when I run the program I only get the "Flush" and "Straight Flush" hands. Do I need to change the getPairs and getKind methods to get the 'result' from the int value() method from the Card class rather than 'face' from the getFace() method?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.