Moonket
Moonket

Reputation: 11

How can I split a deck of 52 cards into 4 hands of 13 in Java?

For this project we are not able to use any collection classes. I have tried using a loop to create 4 arrays which each hold 13 cards, so they can later be sorted and presented to user. I can't work out how to populate 4 arrays with cards from the deck

My deal method:

public void deal() {
        for (int i = 0; i < 4; i++) {
            Card[] hand = new Card[13];
            for (int j = 0; j < 13; j++) {
                hand[j] = deckOfCards[j];
                j++;
            }
        }
    }

Upvotes: 0

Views: 390

Answers (1)

Anuj
Anuj

Reputation: 1665

It seems you have made a logical error. Lets make a dry run. The outer loop runs 4 times.

    for (int i = 0; i < 4; i++)

Each time, a new array hand of type Card is created.

    Card[] hand = new Card[13];

Next we move to the j loop which runs 13 times for each value of i from 0-3,

    for (int j = 0; j < 13; j++)

Now inside the elements are stored in the array hand.

     //Logical error
     hand[j] = deckOfCards[j];

Now every time in the hand array, only the first 13 elements of deckOfCards are used. You are not accessing elements from 13-51 of the array deckOfCards. To do that try changing this part of your code to this.

    hand[j] = deckOfCards[j + i*13];

This makes all the elements of deckOfCard to be accessed.

I hope I helped you.

Upvotes: 1

Related Questions