简体   繁体   中英

How to create a deck of cards in Java

*Edit I am unable to use the java collection classes in this project.

I have created my card class and now I need to figure out how to create a deck of cards in my deck class. I am a beginner so sorry if this seems like a very stupid question.

Card Class

Public class Card {
    private final String rank;
    private final String suit;

    public Card(String rank, String suit){
        this.rank = rank;
        this.suit = suit;
    }

    public String getRank(){
        return rank;
    }

    public String getSuit() {
        return suit;
    }

    public String toString(){
        return (this.rank + " of " + this.suit);
    }
}

Deck

String suit[] = {"Hearts", "Clubs", "Diamonds", "Spades"};
String rank[] = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "King", "Queen", "Ace"};


public void DeckOfCards() {


}

Extrapolating from your work, the deck of cards can be represented as an array of 52 Card objects:

String suit[] = {"Hearts", "Clubs", "Diamonds", "Spades"};
String rank[] = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "King", "Queen", "Ace"};
Card[] deck = new Card[52];
//Assigning values to each card in the deck
int ctr = 0;
for (int i = 0; ctr < 4; ++i) {
    for (int j = 0; j < 13; ++j) {
        deck[ctr] = new Card(rank[j], suit[i]);
        ++ctr;
    }
}

In which the variable deck is the desired deck of cards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM