How to mix cards in a Map object with Math.random ()

advertisements

So the problem is I am not getting any card rank or value of card such as a number 2-14 and my characters 'C', 'D', 'H', 'S' seem to get shuffled.

How would I go about shuffling an object containing

new Card(int, char)

with characters 'C', 'D', 'H', 'S' which represent the cards suit.

This code below does not seem to work as in saving any rank numbers.

for (int i = 0; i <= 51; i++)
cards[i] = new Card((int)Math.random() * 52, 'D');

An example of how the shuffling should work if card [14] randomly generates integer 35, then card[14] would swap with card[35].

public void shuffle()
{
    for (int i = 0; i <= 51; i++)
        cards[i] = new Card((int)Math.random() * 52, 'D');

    for (int i = 0; i <= 51; i++) {
        Card temp = cards[i];
        for (int j = 0; j <= 51; j++) {
            cards[i] = cards[j];
            cards[j] = temp;
        }
    }
}


I would suggest you first create the deck, then shuffle it.

// Create deck
Card[] cards = new Card[52];
int i = 0;
for (int v = 2; v <= 14; v++)
    for (char s : "CDHS".toCharArray())
        cards[i++] = new Card(v, s);

// Shuffle
Collections.shuffle(Arrays.asList(cards));