Computer Science Canada

Card/Deck Object Construction

Author:  Albrecd [ Wed Apr 23, 2008 12:33 pm ]
Post subject:  Card/Deck Object Construction

I am making a Blackjack game using Java. Right now I'm working on the Deck and Card objects.
When my deck is instatiated, the constructor add 52 card objects to its array "CardInDeck" (13 of each suit).

Java:

public class BlackJack
{
    public static void main (String[] args)
    {
        Deck Dealer = new Deck() ;
        for (int card = 0; card < 52; card ++)
        {
            //System.out.println(Dealer.CardInDeck[card].CheckCard()[0]) ;
            //System.out.println(Dealer.CardInDeck[card].CheckCard()[1]) ;
        }
    }
}



class Card
{
    private static int[] cardData = new int [2] ;

    public Card (int value, int suit)
    {
        cardData[0] = value ;
        cardData[1] = suit ;
    }
   
    public static int[] CheckCard ()
    {
        return cardData ;
    }
}



class Deck
{
    public Card[] CardInDeck = new Card[52] ;
    private int nextCard = 0 ;
   
    public Deck ()
    {
        for (int suit = 0; suit < 4; suit += 1)
        {
            for (int value = 0; value < 13; value += 1)
            {
                CardInDeck[nextCard] = new Card(value, suit) ;
                //System.out.println (CardInDeck[nextCard].CheckCard()[0]) ;
                //System.out.println (CardInDeck[nextCard].CheckCard()[1]) ;
                nextCard ++ ;
            }
        }
    }
}


If you take the commenting off of the output statements in Deck's constructor method, it shows that the cards have been properly initialized; however, if you instead take the commenting off of the output statements in the main program, every card is shown to have the same value (12) and the same suit (3).

If you could explain to me why this might be, I would greatly appreciate it.

Thanks

Author:  HeavenAgain [ Wed Apr 23, 2008 12:54 pm ]
Post subject:  RE:Card/Deck Object Construction

code:
private static int[] cardData = new int [2] ;
i dont think it should be static but instead it should just be an instance variable and so
code:
public static int[] CheckCard ()
need to be changed too
thats probably why it will always end up as the last value you give which is 12/3?

Author:  jernst [ Thu Apr 24, 2008 8:48 am ]
Post subject:  Re: Card/Deck Object Construction

Yeah that sounds right, because when you make a variable static within a class every instance of the class makes use of the same static variable. So instead of each card having its own card data, every card shares the same data the way your code had it.

Author:  Albrecd [ Thu Apr 24, 2008 11:45 am ]
Post subject:  Re: Card/Deck Object Construction

Thanks for the help; it works now. Smile


: