1

I´m getting error non-static variable deck cannot be referenced from a static context from this piece of code. I would like to understand what wrong is going there. I´m new to java.

public class CardDeck extends java.lang.Object 
{
    private  int size;
    private Stack<Card> deck;
    public CardDeck(int size)
    {
        this.deck = new Stack<Card>();
        this.size = size;
    }
    public static CardDeck createStandardDeck()
    {

            for (int i = 1; i <= 13; i++) { deck.push(new Card(Card.Color.CLUBS,i)); }
            for (int i = 1; i <= 13; i++) { deck.push(new Card(Card.Color.DIAMONDS,i)); }
            for (int i = 1; i <= 13; i++) { deck.push(new Card(Card.Color.HEARTS,i)); }
            for (int i = 1; i <= 13; i++) { deck.push(new Card(Card.Color.SPADES,i)); }
        return deck;
    }
  • first thing no need to extend Object class .Every superclass by default extends Object class.can you post your push method? – santosh gore Mar 03 '17 at 11:03

1 Answers1

1

Change your mathod as follows :

public static CardDeck createStandardDeck() {
    CardDeck myDeck = new CardDeck(13*4);
    for (int i = 1; i <= 13; i++) { myDeck.deck.push(new Card(Card.Color.CLUBS,i)); }
    for (int i = 1; i <= 13; i++) { myDeck.deck.push(new Card(Card.Color.DIAMONDS,i)); }
    for (int i = 1; i <= 13; i++) { myDeck.deck.push(new Card(Card.Color.HEARTS,i)); }
    for (int i = 1; i <= 13; i++) { myDeck.deck.push(new Card(Card.Color.SPADES,i)); }
    return myDeck;
}
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33