0

I am trying to deal a deck of 52 playing cards amongst 4 players equally, meaning they will each have 13 cards each. I can only seem to deal 4 cards each and i'm not sure why. Any help would be great. I have also attached an image of the output : OUTPUT

 public void deals() {
                for (int i = 0; i < 4; i++) {
                    System.out.println("** Player " + (i + 1) + " has been dealt the following cards: **");
                    for (int j = 0; j <4; j++) {
                        //System.out.println(ranks[i + j * 4] + " of " + suits[j]);
                        System.out.println(ranks[i + j] + " of " + suits[j]);

                    }
                }
            }

When I change the 4 to a higher number in System.out.println(ranks[i + j * 4] + " of " + suits[j]);I get an error.

hteuw
  • 11
  • Your first loop indicates the 4 players. Your inner loop seems to view the card dealed. 4x4 is 16. Thus you are missing some cards. How ever post the complte code so we can help you in more detail. – Marcinek Nov 22 '20 at 22:58
  • Welcome to SO! Please avoid referring to your code or data using a link to an image. Instead, add the information directly in your post please. – buddemat Nov 22 '20 at 23:30

1 Answers1

0

It seems that you need to create (and shuffle) a deck of cards first and then to deal the cards to 4 players:

// setup a card deck
List<Card> deck = new ArrayList<>();
for (int i = 0; i < ranks.length; i++) {
    for (int j = 0; j < suits.length; j++) {
        deck.add(new Card(ranks[i], suits[j]));
    }
}
// shuffle
Collections.shuffle(deck);

// deal
int players = 4;
for (int p = 0; p < players; p++) {
    System.out.println("Player " + (p + 1) + " gets these cards:");
    for (int i = 0, n = deck.size() / players; i < n; i++) {
        System.out.println(deck.get(p + players * i));
    }
}

It may be convenient to use Java streams to present the cards as collection of players' lists of cards:


Collection<List<Card>> playerCards = IntStream
        .range(0, deck.size())  // indexes in range [0..52)
        .boxed()
        // "dealing" cards 1 by 1
        .collect(Collectors.groupingBy(i -> i % players, Collectors.mapping(i -> deck.get(i), Collectors.toList())))
        .values();

// print cards per player        
playerCards
        .stream() // stream of List<Card>
        .map(p ->  p.stream()  // stream of Card of the player
                    .sorted()  // if Card class implements Comparable<Card>
                    .map(Card::toString)
                    .collect(Collectors.joining(" ")) // get player's hand
        )
        .forEach(System.out::println);

Sample output (suits are sorted in order ♥ ♦ ♠ ♣):

4♥ J♥ Q♥ K♥ 2♦ 3♦ 6♠ 7♠ 8♠ 10♠ Q♠ A♣ K♣
2♥ 5♦ 6♦ 7♦ 9♦ A♠ 4♠ 9♠ K♠ 2♣ 4♣ 6♣ 10♣
5♥ 6♥ 10♥ 8♦ 2♠ 3♠ J♠ 3♣ 5♣ 7♣ 8♣ 9♣ Q♣
A♥ 3♥ 7♥ 8♥ 9♥ A♦ 4♦ 10♦ J♦ Q♦ K♦ 5♠ J♣
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42