How to shuffle a deck of cards in java?

474    Asked by TanuBakshi in Java , Asked on Oct 18, 2022

The program interacts between cards and four players among whom cards are to be distributed.

The Program do the following function

Creates a deck of cards.

Shuffle the deck.

Shows the deck.

Deal cards equally among four players.

Show the cards of each Player.

Please suggest some better ways of doing this program.

Also suggest new functions and modifications in this program.


Answered by shivani Chavan

Your question - how to shuffle a deck of cards in java can be answered as -


Naming

Singular & plural nouns

A player is a Player not a Player, you should use singular names when you talk about one thing, and plural when you talk about many. ie:

Player[] players = new Player[4];

Avoid redundancy

Try to avoid redundancy in naming, so instead of having:

DeckOfCards.shuffleDeck()

you can write:

DeckOfCards.shuffle()

Keep them simple

There's not much chance here that the reader will think about a loading deck if you simply named your class Deck. In this context, it's pretty obvious that it's a cards' deck.

MISC

Be generic when possible

Try to be as generic as possible, avoid magic values. The size of your deck if the sum of all possible combinations, so for example, taking again the use of enums advised in one of the other answer:

private static final int SIZE = Suit.values().length * Rank.values().length;

Like that, if later you decide to change the type of deck, e.g. removing aces or figures, the change will be reflected automatically in the rest of your code. And you know... «Less code to refactor makes developers happier».

Think about underlying types

You can maybe store just the index of the card, with a simple int. A card can be represented by an index relative to its place in a new deck. [range 0-51].

To retrieve suits and ranks from indexes, depending on how cards are ordered in the deck.

If ordered by rank (A♡, A♢, A♠, A♣, 2♡, 2♢, ..., K♡, K♢, K♠, K♣) :

Rank r = Rank.values()[i / 4];

Suit s = Suit.values()[i % 4];

If ordered by suit (A♡, 2♡, 3♡, ..., J♣, Q♣, K♣) :

Rank r = Rank.values()[i ];

Suit s = Suit.values()[i / 13];



Your Answer

Interviews

Parent Categories