Search code examples
javapoker

Generating poker hands for N number of players (five cards each)


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.


Solution

  • 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];