为N个玩家生成扑克牌(每个五张牌)

时间:2012-02-19 17:55:10

标签: java poker

问题:编写一个程序Deal.java,它接受一个命令行参数N并从一个洗牌的牌组中打印N个扑克牌(每张五张牌),用空行分隔。

我有什么:

public static void main(String[] args)
{
    int N = Integer.parseInt(args[0]);


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

    // initialize cards in a deck
    String[] deck = new String[suit.length * rank.length];
    for (int i = 0; i < rank.length; i++)
        for (int j = 0; j < suit.length; j++)
            deck[rank.length*i + j] = rank[i] + " of " + suit[j];

    // shuffle deck
    int d = deck.length;
    for (int i = 0; i < d; i++)
    {
        int r = i + (int) (Math.random() * (d-i));
        String temp = deck[r];
        deck[r] = deck[i];
        deck[i] = temp;
    }

    // repeat for N number of people
    for (int t = 0; t < N; t++)
    {
        // print 5 random cards
        for (int i = 0; i < 5; i++)
            System.out.print(deck[i] + " ");
        System.out.println();
    }   


} 

有谁能告诉我这里我做错了什么?我收到一个错误ArrayIndexOutOfBoundsExceptions,不知道为什么。这是我书中练习的问题,而不是作业。

3 个答案:

答案 0 :(得分:2)

我假设你在这一行上得到了一个数组索引超出范围的异常:

deck[rank.length*i + j] = rank[i] + " of " + suit[j];

你一定有这个意思:

deck[suit.length*i + j] = rank[i] + " of " + suit[j];

答案 1 :(得分:2)

除了ruakh发现的索引错误之外,您正在打印同一只手N次:

// repeat for N number of people
for (int t = 0; t < N; t++)
{
    // print 5 random cards
    for (int i = 0; i < 5; i++)
        System.out.print(deck[i] + " ");
    System.out.println();
}

要打印不同的牌,请使用另一个索引变量

// repeat for N number of people
int j = 0
for (int t = 0; t < N; t++)
{
    // print 5 random cards
    for (int i = 0; i < 5; i++, j++)
        System.out.print(deck[j] + " ");
    System.out.println();
}   

答案 2 :(得分:0)

我看不出问题似乎正常,请尝试提供更多详细信息。

你应该改进的是:

检查参数是否在开头正确设置:

public static void main(String[] args)
{
    int N = Integer.parseInt(args[0]);

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

    if(N < 0 || N > suit.length * rank.length)
      throw new IllegalArgumentException("A number between 0 and " + suit.length * rank.length + "should be provided as argument");