Problem: Write a program Deal.java that takes an command-line argument N and prints N poker hands (five cards each) from a shuffled deck, separated by blank lines.

What I have:

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


} 

Can anybody tell me what I'm doing wrong here? I'm getting an error ArrayIndexOutOfBoundsExceptions, not sure why. This is a problem out of an exercise set from my book, not homework.

有帮助吗?

解决方案

I assume you're getting an array-index-out-of-bounds exception on this line:

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

where you must have meant this:

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

其他提示

In addition to the index error spotted by ruakh, you are printing out the same hand N times:

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

To print out different hands, use another index variable,

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

I can't see what's the problem seems to work ok, try to give some further details.

Something you should improve is:

Check the parameter is set at the beginning properly:

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");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top