PenguinProgrammer
PenguinProgrammer

Reputation: 141

Objects and ArrayLists in Java

For the assignment I'm working on I am suppose to make a crazy 8s game. What we are instructed to do is create a class that creates a new card and then a deck class that adds cards to a deck. Below is my code. My problem is when I try to print the cards in the deck, they all show up as 'KC' = King of Clubs. This is our first class assignment so I hope I'm just missing something fundamental.

My Card Class:

    public class Card {

        static int face;
        static int suit;
        static String[] faces = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
        static String[] suits = {"H", "D", "S", "C"};

        public Card(int face, int suit) {
            this.face = face;
            this.suit = suit;
        }

        public static String cardString(){
            return faces[face - 1] + suits[suit - 1];
        }



    }

My Deck Class:

import java.util.List;
import java.util.ArrayList;

public class Deck {

    static List<Card> deck = new ArrayList<Card>(); 

    public Deck() {
        for (int j = 1; j <= 4; j++){
            for (int i = 1; i <= 13; i++){
                Card c = new Card(i, j);
                // System.out.println(c.cardString());
                deck.add(c);
            }
        }
    }

    public static void main(String[] args) {
        Deck d = new Deck();
        for(Card card : d.deck){
            System.out.println(card.cardString());
        }
    }

}

Upvotes: 1

Views: 331

Answers (1)

Rahul
Rahul

Reputation: 45060

That is because both face and suit are static. All static fields of a Class are shared by all the instance of it. That is why for every Card() you create in the values are overridden and you end up with the last values as KC reflecting for all the instances. You need to make them instance variables, instead of static.

// In Card class
int face; // Instance variable
int suit; // Instance variable

That way, each instance of the Card will their own separate copy of face and suit.

As a side note, since the deck list in your Deck class is also static, it'll show the same behavior. Also, since its static, you need to access is using the ClassName and not the instance. Something like this

for(Card card : Deck.deck){ // access using class name instead of instance

Upvotes: 5

Related Questions