Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: NullPointerException in Poker's program

  1. #1
    Junior Member
    Join Date
    Apr 2009
    Posts
    12
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default NullPointerException in Poker's program

    Hi, working on a poker program(isn't everybody?) After searching for hours on the web I'm hoping someone here can help me. Here is the problematic snippet below.

    // this part works fine
    for (Player player : players){
                player = new Player();
                player.pocketCard1 = new Card(deck.deal());
                System.out.print(player.pocketCard1.toString() + " ");
                player.pocketCard2 = new Card(deck.deal());
                System.out.print(player.pocketCard2.toString() + " ");
            }
     
    // this part throws a null pointer exception
            System.out.print(players[0].pocketCard1.toString() + " ");

    It seems like the assignments I made to pocketCard1 simply disappear when the for loop ends. Can I not use a for loop to set data members? The second piece of code does exactly the same thing as the first.
    I'm pulling my hair out here.
    -dean_martin
    Last edited by dean_martin; April 21st, 2009 at 01:19 AM.


  2. #2
    Junior Member
    Join Date
    Apr 2009
    Posts
    12
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: crazy NullPointerException

    btw I forgot to introduce myself.

    I am a new programmer in the San Diego area. I just graduated from a computer information systems

    diploma level course and I'm close to an AA degreee. I started by learning Java, learned bits and pieces of

    other languages too. Now that I have a school break, I'm going back to my Java roots to brush up.

    I'm happy to see some concepts click which made no sense 7 months ago, but I feel like I don't have much

    depth of knowledge, though having a slightly better breadth and flexiblity with other languages.

    peace
    dean_martin

  3. #3
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: crazy NullPointerException

    Hello dean_martin and welcome to the forums

    Could you please attach all of the code so I can compile it and see the error for myself?
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  4. #4
    Junior Member
    Join Date
    Apr 2009
    Posts
    12
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: crazy NullPointerException

    Ok here is everything:

    edit: I'm using NetBeans 6.5.1

    public enum Suit {
       DIAMONDS,
       CLUBS,
       HEARTS,
       SPADES
     
    }
     
    public enum Rank {
        DEUCE, THREE, FOUR, FIVE, SIX, SEVEN,
        EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
    }
     
    public class Card{
        Rank rank;
        Suit suit;
     
        public Card(){}
     
        public Card(Card card) {
            this.rank = card.rank;
            this.suit = card.suit;
        }
     
        public Card(Rank rank, Suit suit) {
            this.rank = rank;
            this.suit = suit;
        }
     
        public Suit getSuit() {
            return suit;
        }
     
        public Rank getRank() {
            return rank;
        }
     
        @Override
        public String toString() {
            return rank + " of " + suit;
        }
    }
     
    public class Deck{
        Card[] cards = new Card[52];
        int index;
     
        public Deck() {
            index = 0;
            int i = 0;
            for (Suit suit : Suit.values()) {
                for (Rank rank : Rank.values()) {
                    cards[i++] = new Card(rank, suit);
                }
            }
        }
     
        @Override
        public String toString(){
            String allCards = "";
            for (Card card : cards){
                allCards += card.toString() + "\n";
            }
            return allCards;
        }
     
        public void shuffle(){
            for (int i = 0; i < this.cards.length; i++){
                int randomIndex = (int) (Math.random() * this.cards.length);
                Card current = this.cards[i];            
                this.cards[i] = this.cards[randomIndex];
                this.cards[randomIndex] = current;
            }
        }    
     
        public Card deal(){
            return this.cards[index++];
        }
    }
     
    public class Player {
        String name;
        int bankroll;
        int chipstack;
        Card pocketCard1;
        Card pocketCard2;
        String handRank;
     
        public Player(){
        }
     
        public void setPocketCards(Card card1, Card card2){
            pocketCard1 = card1;
            pocketCard2 = card2;
        }
    }
     
    public class Main{
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {        
            Deck deck = new Deck();
            deck.shuffle();
     
            int numberOfPlayers = 2;
            Player[] players = new Player[numberOfPlayers];
            for (Player player : players){
                player = new Player();
                player.pocketCard1 = new Card(deck.deal());
                System.out.print(player.pocketCard1.toString() + " ");
                player.pocketCard2 = new Card(deck.deal());
                System.out.print(player.pocketCard2.toString() + " ");
            }
            System.out.print(players[0].pocketCard1.toString() + " ");
     
    //        for (Player player : players){
    //            System.out.println("" +
    //            player.pocketCard1.toString() +
    //            player.pocketCard2.toString());
    //        }
     
            Card[] communityCards = new Card[5];
            for (Card card : communityCards){
                card = new Card(deck.deal());
     
    //        for (Card card : communityCards){
    //            System.out.println(" " + card.toString());
            }
     
     
        }
     
    }
    Last edited by dean_martin; April 21st, 2009 at 04:07 AM.

  5. #5
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: crazy NullPointerException

    Thanks for that dean,

    I can see the exception. I will look into it now..
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  6. #6
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: crazy NullPointerException

    Dean, if this wasn't generating an exception, what is your expected output for:

    System.out.print(players[0].pocketCard1.toString() + " ");

    ?
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  7. #7
    Junior Member
    Join Date
    Apr 2009
    Posts
    12
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: crazy NullPointerException

    Quote Originally Posted by JavaPF View Post
    Dean, if this wasn't generating an exception, what is your expected output for:

    System.out.print(players[0].pocketCard1.toString() + " ");

    ?
    Thanks for looking into this. The program randomly shuffles the deck, so the output for:
    System.out.print(players[0].pocketCard1.toString() + " ");
    should be a random card name, such as:
    SIX of HEARTS

    I am printing the card for testing and debugging purposes. My real problem seems to be assigning values to the
    pocketCard1 and pocketCard2 fields of a player object.

  8. #8
    Junior Member
    Join Date
    Apr 2009
    Posts
    12
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: crazy NullPointerException

    I changed the for loop from enhanced to regular and the exception is not being thrown anymore.
    However, it feels like a patchjob and I'm not satisfied with it.

    Here is the snippet from the top post, slightly modified:

    Deck deck = new Deck();
            deck.shuffle();
     
            int numberOfPlayers = 2;
            Player[] players = new Player[numberOfPlayers];
     
    /*   If I use this enhanced for loop to assign pocketCard1, I can then reference pocketCard1
     *   within the loop. Then if I try to reference pocketCard1 immediately following the loop,
     *   I get the NullPointerException
     */     
    //        for (Player player : players){
    //            player = new Player();
    //            player.pocketCard1 = new Card(deck.deal());
    //            System.out.print(player.pocketCard1.toString() + " ");          
    //        }
    //        System.out.print(players[0].pocketCard1.toString() + " ");// This line throws NullPointerException.
     
    /*  I'm using a standard for loop to assign pocketCard1, then I can reference pocketCard1 
         from withing the for loop or afterward
            for (int i = 0; i < numberOfPlayers; i++){
                players[i] = new Player();
                players[i].pocketCard1 = new Card(deck.deal());
                System.out.print(players[i].pocketCard1.toString() + " ");
            }
            System.out.print(players[0].pocketCard1.toString() + " ");// This line does not.

    I am trying to learn and use best practices over getting this done quickly. Therefore, I would like to understand why the enhanced for loop is not working like I think it should. I could just use the standard form, but according to the Sun Tutorial an enhanced for loop should be used when you want to cycle through each item of an array.

  9. #9
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: crazy NullPointerException

    Hello dean,

    The enhanced for loop is something that is reasonably new to myself. I have always used the regular for loop to print array data in the past. This will not cause any performance issues so there is no reason not to use regular for loops but like you say, its best practise to keep up with coding standards.

    players[0] is being returned as null. I'm having a play with it now.

    You will have to excuse my slow replies. I am at work so doing 10000 things at once
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  10. #10
    Junior Member
    Join Date
    Apr 2009
    Posts
    12
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Re: crazy NullPointerException

    I found this on a Sun webpage.
    It's important to note that the enhanced for loop can't be used everywhere. You can't use the enhanced for loop:

    * To remove elements as you traverse collections
    * To modify the current slot in an array or list
    * To iterate over multiple collections or arrays
    I assume that trying to assign within the loop breaks the second rule. I am confused as to the reasoning
    behind the rule, but my issue is solved.

  11. #11
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: crazy NullPointerException

    Ah OK yes that makes sense. Learning new things every day!

    I'm glad you have resolved this. Thank you for marking your thread as solved
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

Similar Threads

  1. Java NullPointer Exception in Server chat program
    By Valtros in forum Exceptions
    Replies: 1
    Last Post: May 8th, 2009, 05:06 AM
  2. Replies: 3
    Last Post: February 26th, 2009, 03:04 AM
  3. NullPointerException in Java
    By jazz2k8 in forum Exceptions
    Replies: 9
    Last Post: June 1st, 2008, 05:59 PM