卡片组和洗牌方法

时间:2017-06-13 15:33:38

标签: java

我正在尝试实现卡片组并为其创建一个shuffle方法。当我在主方法中编写它时,一切都工作得很好,但是当我尝试使用不同的方法时,即使使用了shuffle方法,我也得到了卡的原始序列(它不是随机播放)。我做错了什么?

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();

    }

}

2 个答案:

答案 0 :(得分:9)

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

始终为零,因为它会计算(int) Math.random()(零),然后将其乘以cards.length

你的意思是:

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

答案 1 :(得分:-3)

而不是依赖math.random,java有一个随机类,它使用种子进行自己的随机化:

Random random = new Random(System.currentTimeMillis());

int m = random.nextInt(cards.length);
int n = random.nextInt(cards.length);