Need help with a deck of cards homework!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • garyrowell
    New Member
    • Mar 2008
    • 6

    Need help with a deck of cards homework!

    I have been at this programme for hours trying to work out what is wrong. Any help would be very much appricated. Here is the breif I received.

    The program
    This week you are going to write three classes: Card.java, Deck.java and DeckTester.java . The specification for each class is given below.

    Card.Java
    This is a simple class that represents a playing card.

    Card has two attributes:
    • rank which is a String that represents the value of a card. It takes the values “ACE,”2”,”3”,…, ”JACK”,”QUEEN”, ”KING”; and
    • suit a String which takes the values “SPADES”,”DIAMO NDS”,”CLUBS”,”H EARTS”.

    The class has a single constructor which takes two parameters: the first is an int that represents the rank in the range 1 to 13; the second a String representing the suit. The constructor must convert the int into an appropriate String value.

    Additionally there are two methods that return String representations of the suit and rank respectively.

    A skeleton of the class is provided. You have to complete the missing components. This file can be found on Blackboard with the homework specification.

    Deck.java
    This class represents a deck of playing cards.

    This class has two attributes: an array of type Card holding the 52 cards of the deck; an int that holds the number of cards in the deck, (this attribute is not used in this homework but may be used later);

    A skeleton of the class is also provided. You have to complete the missing components. This file can be found on Blackboard with the homework specification.

    DeckTester.java
    This class contains the main method. Its purpose is to allow you to demonstrate that your deck class works as anticipated. In particular you need to:
    • Create an instance of the Deck class;
    • Confirm that the constructor works correctly;
    • Confirm that shuffle works correctly.


    My tutor gave me a little bit of the code and some comments on where to fill in the missing code. So far I have this:

    Code:
    public class Deck
    {
        private Card [] deck;
        private int numberOfCards;
    
        /**
         * Creates a deck of 52 playing cards
         * The deck is set up in the order SPADES, DIAMONDS, CLUBS,HEARTS
         */
        public Deck()
        {
        	String [] suits = {"SPADES","DIAMONDS","CLUBS","HEARTS"};
        	
        	for ( int suit = 0; suit <= 3; suit++ )
        	{
        		for ( int rank = 1; rank <= 13;rank++ )
        		{
        			numberOfCards = 0;
        			deck [numberOfCards] = new Card(rank,suit);
        			numberOfCards ++;
        		}
        	}
    
           numberOfCards = 52;
    
        }
        
        /**
         * shuffles the deck of cards.
         * 
         */
      /*  public void shuffle()
        {
            Card temp;        // Temporary object to hold value whilst swapping
    
             //loop through each card in the deck and swap it with some random card.
             //FOR EACH CARD IN THE DECK
             {
                     int rand = (int)(Math.random()*52);
                     //TAKE THE CURRENT CARD...
                     //AND SWAP IT WITH THE RAND CARD...
               }
          }  
       
        /**
         * Returns a representation of the deck as a string
         * one card per line
         * @return     the deck as a String
         */
        public String toString()
        {
        	String deckString = "New deck created ";
        	for (int cards =0; cards <52; cards++)
    		{
    			deckString = deckString + deck[cards] + "\n";
    			
    		}
    		System.out.println(deckString);
    		return deckString;
        }
    }
    
    
    ----------------------------------------------------------------------------------------------
    /**
     * This class represents a simple playing card.
     * The attributes of the card are both of type String:
     *   rank - takes values ACE,1,2,3,.., JACK, QUEEN, KING
     *   suit - takes values SPADES, DIAMONDS,CLUBS, HEARTS
    */
    public class Card 
    {
        
        private String rank;
        private String suit;
    
        /*Constructor for objects of class Card
         * Each card has a rank and a suit.   No checks are made for invalid values
         * @param  rank   an int representing the valus of the card, range 1..13
         * @param  suit   a String representing the suit of card: values                      
                  "SPADES","DIAMONDS","CLUBS","HEARTS"
         */
        public Card(int rank, int suit)
        {
            if(suit == 0)
            {
            	this.suit = "Spades";
            }
            else if(suit == 1)
            {
            	this.suit = "Diamonds";
            }
            else if(suit ==2)
            {
            	this.suit = "Clubs";
            }
            else
            {
            	this.suit = "Hearts";
            }
    
    
            // must convert the integer value of rank to an appropriate String
            if (rank == 1)
            {
            	this.rank = "Ace";
    		}
            else if (rank == 11)
            {
            	this.rank = "Jack";
            }
            else if (rank == 12)
            {
            	this.rank = "Queen";
            }
            else if (rank == 13)
            {
            	this.rank = "King";
            }
    		else
    		{
    			this.rank = "" + rank;
          	}
    	}
    	public String getSuit() 
    	{
    		return suit;
    	}
    	public String getRank() 
    	{
    		return rank;
    	}
    
    }
    -------------------------------------------------------------------------------
    public class DeckTester
    {
    	public static void main(String[] args)
    	{
    		Deck deck1 = new Deck();;
    		System.out.println(deck1.toString());
    				
    	}
    }
    I know I have not entered the code yet to shuffle the cards but I know how to do this and will add the code in later I just want to get the cards printing out in order first.

    The project complies properly but when I run it I get this error:

    Exception in thread "main" java.lang.NullP ointerException
    at Deck.<init>(Dec k.java:20)
    at DeckTester.main (DeckTester.jav a:5)
    Press any key to continue...

    I realise there is a problem at line 20 in the Deck class and line 5 in the DeckTester Class. or the problem is elsewhere causing these too problems. But I have sat here for hours trying to work out what is wrong and I cant see anything.

    Yet again any help would be much appricated.
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    You never initialize your deck array in the constructor, so it doesn't have a size or any contents. As such, the first time you try to access it, you get the NullPointerExce ption. Add a statement "deck = new Card[size of the deck];" and then just make sure that you don't exceed the bounds of the array anywhere in your code to avoid these errors in the future.

    Comment

    • sukatoa
      Contributor
      • Nov 2007
      • 539

      #3
      what is
      Code:
      private Card [] deck;
      @ line 3?
      Can you discuss it for me? Why you just allocate it without initializing?

      It looks familiar to me... Maybe you don't initialized it....

      Wondering,
      Sukatoa

      Comment

      • garyrowell
        New Member
        • Mar 2008
        • 6

        #4
        Originally posted by Laharl
        You never initialize your deck array in the constructor, so it doesn't have a size or any contents. As such, the first time you try to access it, you get the NullPointerExce ption. Add a statement "deck = new Card[size of the deck];" and then just make sure that you don't exceed the bounds of the array anywhere in your code to avoid these errors in the future.
        would I add that in to the card constructor? or too the deck class?

        Comment

        • garyrowell
          New Member
          • Mar 2008
          • 6

          #5
          Originally posted by sukatoa
          what is
          Code:
          private Card [] deck;
          @ line 3?
          Can you discuss it for me? Why you just allocate it without initializing?

          It looks familiar to me... Maybe you don't initialized it....

          Wondering,
          Sukatoa

          It was given to me in the skelton of the code from my tutor. I have no Idea what it does

          Comment

          • garyrowell
            New Member
            • Mar 2008
            • 6

            #6
            Originally posted by garyrowell
            would I add that in to the card constructor? or too the deck class?
            Ahhh Ive worked out where that goes thanks! Now however I have a different problem the string prints out giberish! any ideas?

            Comment

            • garyrowell
              New Member
              • Mar 2008
              • 6

              #7
              Right so I am still at this I have updated the card and deck class they now look like this
              Code:
              public class Deck
              {
                  private Card [] deck;
                  private int numberOfCards;
              
                  /**
                   * Creates a deck of 52 playing cards
                   * The deck is set up in the order SPADES, DIAMONDS, CLUBS,HEARTS
                   */
                  public Deck()
                  {
                  	deck = new Card[52];
                  	numberOfCards = 0;
                  	String [] suits = {"SPADES","DIAMONDS","CLUBS","HEARTS"};
                  	for ( int suit = 0; suit <= 3; suit++ )
                  	{
                  		for ( int rank = 1; rank <= 13;rank++ )
                  		{
                  			
                  			deck [numberOfCards] = new Card(rank,suits[suit]);
                  			numberOfCards ++;
                  		}
                  	}
              
                     
              
                  }
                  
                  /**
                   * shuffles the deck of cards.
                   * 
                   */
                /*  public void shuffle()
                  {
                      Card temp;        // Temporary object to hold value whilst swapping
              
                       //loop through each card in the deck and swap it with some random card.
                       //FOR EACH CARD IN THE DECK
                       {
                               int rand = (int)(Math.random()*52);
                               //TAKE THE CURRENT CARD...
                               //AND SWAP IT WITH THE RAND CARD...
                         }
                    }  
                 
                  /**
                   * Returns a representation of the deck as a string
                   * one card per line
                   * @return     the deck as a String
                   */
                  public String toString()
                  {
                  	String deckString = "New deck created\n";
                  	for (int cards =0; cards <=51; cards++)
              		{
              			deckString = deckString + deck[cards] + "\n";
              		}
              		return deckString;
                  }
              }
              
              
              
              
              
              
              
              
              /**
               * This class represents a simple playing card.
               * The attributes of the card are both of type String:
               *   rank - takes values ACE,1,2,3,.., JACK, QUEEN, KING
               *   suit - takes values SPADES, DIAMONDS,CLUBS, HEARTS
              */
              public class Card 
              {
                  
                  private String rank;
                  private String suit;
                  // MISSING CODE
              
                  /*Constructor for objects of class Card
                   * Each card has a rank and a suit.   No checks are made for invalid values
                   * @param  rank   an int representing the valus of the card, range 1..13
                   * @param  suit   a String representing the suit of card: values                      
                            "SPADES","DIAMONDS","CLUBS","HEARTS"
                   */
                  public Card(int rank, String suits)
                  {       
                      this.suit = suits;
              
              
                      // must convert the integer value of rank to an appropriate String
                      if (rank == 1)
                      {
                      	this.rank = "Ace";
              		}
                      else if (rank == 11)
                      {
                      	this.rank = "Jack";
                      }
                      else if (rank == 12)
                      {
                      	this.rank = "Queen";
                      }
                      else if (rank == 13)
                      {
                      	this.rank = "King";
                      }
              		else
              		{
              			this.rank = "" + rank;
                    	}
              	}
              	public String getSuit() 
              	{
              		return suit;
              	}
              	public String getRank() 
              	{
              		return rank;
              	}
              	public String toString() //add to the .toString method to show all attributes of rectangle
              	{
              		String deckString = new String (rank + " " + suit + super.toString());
                  	return deckString;
              	}
              
              }
              now I am getting an output with the rank and suit of the card however I also get something else afterwards that I cant get rid of which is this:

              New deck created
              Ace SPADESCard@82ba 41
              2 SPADESCard@923e 30
              3 SPADESCard@130c 19b
              4 SPADESCard@1f6a 7b9
              5 SPADESCard@7d77 2e
              6 SPADESCard@11b8 6e7
              7 SPADESCard@35ce 36
              8 SPADESCard@757a ef
              9 SPADESCard@d9f9 c3
              10 SPADESCard@9cab 16
              Jack SPADESCard@1a46 e30
              Queen SPADESCard@3e25 a5
              King SPADESCard@1982 1f
              Ace DIAMONDSCard@ad dbf1
              2 DIAMONDSCard@42 e816
              3 DIAMONDSCard@93 04b1
              4 DIAMONDSCard@19 0d11
              5 DIAMONDSCard@a9 0653
              6 DIAMONDSCard@de 6ced
              7 DIAMONDSCard@c1 7164
              8 DIAMONDSCard@1f b8ee3
              9 DIAMONDSCard@61 de33
              10 DIAMONDSCard@14 318bb
              Jack DIAMONDSCard@ca 0b6
              Queen DIAMONDSCard@10 b30a7
              King DIAMONDSCard@1a 758cb
              Ace CLUBSCard@1b67f 74
              2 CLUBSCard@69b33 2
              3 CLUBSCard@173a1 0f
              4 CLUBSCard@530da a
              5 CLUBSCard@a62fc 3
              6 CLUBSCard@89ae9 e
              7 CLUBSCard@1270b 73
              8 CLUBSCard@60aeb 0
              9 CLUBSCard@16caf 43
              10 CLUBSCard@66848 c
              Jack CLUBSCard@8813f 2
              Queen CLUBSCard@1d58a ae
              King CLUBSCard@83cc6 7
              Ace HEARTSCard@e097 13
              2 HEARTSCard@de6f 34
              3 HEARTSCard@156e e8e
              4 HEARTSCard@47b4 80
              5 HEARTSCard@19b4 9e6
              6 HEARTSCard@10d4 48
              7 HEARTSCard@e0e1 c6
              8 HEARTSCard@6ca1 c
              9 HEARTSCard@1bf2 16a
              10 HEARTSCard@12ac 982
              Jack HEARTSCard@1389 e4
              Queen HEARTSCard@c20e 24
              King HEARTSCard@2e72 63

              Press any key to continue...

              any ideas on how to get rid of that?

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #8
                Originally posted by garyrowell
                public String toString() //add to the .toString method to show all attributes of rectangle
                {
                String deckString = new String (rank + " " + suit + super.toString( ));
                return deckString;
                }
                [/CODE]

                now I am getting an output with the rank and suit of the card however I also get something else afterwards that I cant get rid of which is this:

                New deck created
                Ace SPADESCard@82ba 41
                // etc etc

                Press any key to continue...

                any ideas on how to get rid of that?
                Why are you calling method super.toString( )? The superclass of the Card class
                is the Object class. Its toString() method prints the class name (a Card), an @-sign
                and the hash code of the object, so that's what you see. Leave that call out, simply
                do:

                [code=java]
                public String toString() { return rank + " " + suit; }
                [/code]

                kind regards,

                Jos

                Comment

                • garyrowell
                  New Member
                  • Mar 2008
                  • 6

                  #9
                  Originally posted by JosAH
                  Why are you calling method super.toString( )? The superclass of the Card class
                  is the Object class. Its toString() method prints the class name (a Card), an @-sign
                  and the hash code of the object, so that's what you see. Leave that call out, simply
                  do:

                  [code=java]
                  public String toString() { return rank + " " + suit; }
                  [/code]

                  kind regards,

                  Jos
                  Fantastic that works! Its always something so minor, i had left super in by accident because I copied from an old programme of mine.

                  Thanks very very much everyone!

                  Comment

                  Working...