Nilesh Kumar Nilesh Kumar -4 years ago 51
Java Question

Deck of Cards and shuffle method

I'm trying to implement deck of cards and create a shuffle method for it. Everything is working fine when I'm writing it in the main method but when I'm trying to do it using different methods then even after using shuffle method I'm getting the original sequence of the cards (it is not shuffling). What I'm doing wrong?

import java.util.*;

public class DeckOfCards {

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

private int[] cards;
public DeckOfCards(){

cards = new int[52];
for(int i =0; i < 52; i++){
cards[i] = i;
}
}

public void shuffle(int num){

for(int i = 0; i < num; i++){
int m = (int)Math.random() * cards.length;
int n = (int)Math.random() * cards.length;

int t = cards[m];
cards[m] = cards[n];
cards[n] = t;
}

}

public void display(){
for(int i = 0; i < 52; i++){
String suit = suits[cards[i]/13];
String rank = ranks[cards[i] % 13];
System.out.println(rank+" of "+suit);
}
}


public static void main(String[] args) {
// TODO Auto-generated method stub

DeckOfCards d = new DeckOfCards();
d.display();
d.shuffle(50);
d.display();

}

}

Answer Source

This

int m = (int)Math.random() * cards.length;

is always zero, because it calculates (int) Math.random() (zero) and then multiplies it by cards.length.

What you meant was:

int m = (int) (Math.random() * cards.length);
int n = (int) (Math.random() * cards.length);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download