在Java中选择随机卡

时间:2015-02-24 16:03:20

标签: java random

我是java编程的新手,已经开始创建扑克游戏了。到目前为止已经创建了卡片和卡片,但我希望能够选择一张随机卡片,但我不想洗牌。

到目前为止,这是我的代码:

import java.util.ArrayList;
import java.util.List;


public class PockerMain {

    public PockerMain() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        List<PokerCard> deck = cardDeck();
        for (int i = 0; i < deck.size(); i ++)
        {
            PokerCard card = deck.get(i);
            System.out.println(card);
        }

    }
    private static PokerCard createCard (short suit, short rank)
    {
        PokerCard card = new PokerCard (suit, rank);
        return card;
    }
    private static List<PokerCard> cardDeck ()
    {
        List<PokerCard> deck = new ArrayList<PokerCard> ();
        for (int i = 0; i < 4; i ++)
        {
            for (int j = 0; j < 13; j ++)
            {
                PokerCard card = createCard ((short)i, (short)j);
                deck.add(card);
            }

        }
        return deck;
    }
}

2 个答案:

答案 0 :(得分:0)

尝试Random.nextInt,它会给出0到n-1之间的随机数。如下所示:

Random random = new Random();
int nextCardToPick = random.nextInt(deck.size());//get random number in range 0 - deck.size (assuming 52 cards then it will give value between 0 -51)
System.out.println(deck.get(nextCardToPick));//access by index

答案 1 :(得分:0)

不使用Random对象:     PokerCard rCard = deck.get((int)(Math.random()* deck.size()));