Velislav Rumenov
Velislav Rumenov

Reputation: 19

I am confused on how to add "ranks" to my DeckOfCards lab

everyone, I am trying to add an array named ranks containing the ranks of the cards such as 1 having a rank of 1, and the ace having 11 or 1. I already made a face array and suit array, all I need is ranks and I'm confused on how to actually add that to the deck array which gets printed at the end.

public class DeckOfCards{
    public static void main(String[] args) {
        String[] s = {
            "Clubs", "Diamonds", "Hearts", "Spades"
        };

        String[] face = {
            "2", "3", "4", "5", "6", "7", "8", "9", "10",
            "Jack", "Queen", "King", "Ace"
        };
        int n = s.length * face.length;
        String[] deck = new String[n];
        for (int i = 0; i < face.length; i++) {
            for (int j = 0; j < s.length; j++) {
                deck[s.length*i + j] = face[i] + ", " + s[j];
            }
        }
        for (int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n-i));
            String temp = deck[r];
            deck[r] = deck[i];
            deck[i] = temp;
        }
        for (int i = 0; i < n; i++) {
            System.out.println(deck[i]);
        }
    }

}

Upvotes: 1

Views: 60

Answers (2)

Carrein
Carrein

Reputation: 3371

You could create a Card class which is then added to an arraylist of cards. This class can encapsulate the Rank, Suit and Face information of each card.

class Card {
  private ArrayList≤Integer≥ rank = new ArrayList<>();
  private String suit;
  private String face;

  public Card(int newRank, String newSuit, String newFace){
    this.rank.add(newRank);
    this.suit = newSuit;
    this.face = newFace;
  }
  //additional methods, getters/setters.
}

You can populate your deck by creating an arraylist of Card.

Arraylist<Card> deck = new ArrayList<>();

Then add to your deck by iterating through the arrays.

for(int j = 0; j < suitArray.length; j++){
    for(int k = 0; k < faceArray.length; k++){
        deck.add(new Card(k, suitArray[j], faceArray[k]));
    }
}

This only works for incremental ranks i.e. ACE = 11, King = 10 .. ONE = 1.

If you need different Rank weights, you can try checking the card you would like to assign an additional weight after populating the deck.

for(Card c : deck){
 if (c.getName.equals("ACE"))
    c.addRank(11);
  }
}

Upvotes: 1

uli
uli

Reputation: 671

The easiest way will be to create additional array to store ranks, for example:

String[] ranks = {"1", "2", "3", "4", "5", "6", "7", "8", "9",
    "10", "11", "12", "13"};

And update deck population to:

deck[s.length*i + j] = face[i] + ", " + s[j] + ", rank: " + ranks[i];

The better solution will be to create Card class to store all data.

Upvotes: 0

Related Questions