Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Print deck of cards in Java with Source Code

In this post, I will be sharing how to print a Deck of cards in Java with source code. We all know that there is a total of 52 cards in a deck and they belong to one of the four suits(Spade, Heart, Diamond, and Club).

Read Also: Dice Roll program in Java

Let's dive deep into the topic:

Print Deck of Cards - Java Program

We will perform the below steps to write a Java program for printing a deck of cards:

1. We will create two string arrays named cardRank and cardSuit.

2. We will create another array named deckOfCards of length 52 to represent the deck of cards.

3. We will initialize the deck with default values by iterating over cardSuit and cardRank in a nested loop.

4. We will use Math.random() function to shuffle the deck of cards. It returns a floating-point number between [0-1) where 0(inclusive) and 1(exclusive).


public class DeckOfCards {
public static void main(String args[]) {

int deckLength = 52;
String[] deckOfCards = new String[deckLength];

String[] cardRank = new String[13];
int rankLength = cardRank.length;

String[] cardSuit = {"Spades", "Hearts", "Diamonds", "Clubs"};
int suitLength = cardSuit.length;

for (int i = 1; i cardRank.length ; i++)
{
if(i == 1)
{
cardRank[i] = "Ace";
}
else if(i == 11)
cardRank[i] = "Jack";
else if(i == 12)
cardRank[i] = "Queen";
else if(i == 13)
cardRank[0] = "King";
else
{
cardRank[i] = Integer.toString(i);
}
}

for(int i = 0; i rankLength ; i++)
{
for(int j = 0; j suitLength ; j++)
{
deckOfCards[(i*suitLength)+j] = cardRank[i] + " of " + cardSuit[j];
}
}

for(int i = 0; i deckLength; i++)
{
int index = (int) (Math.random() * (deckLength -i)) + i;
String temp = deckOfCards[index];
deckOfCards[index] = deckOfCards[i];
deckOfCards[i] = temp;
}
for(int i = 0; i deckLength ; i++)
{
System.out.println(deckOfCards[i]);
}
}
}


Output:
9 of Diamonds
7 of Diamonds
King of Spades
4 of Hearts
7 of Hearts
7 of Clubs
King of Hearts
.....
6 of Spades
6 of Clubs
9 of Hearts


That's all for today. Please mention in the comments if you have any questions related to how to print a deck of cards in Java with source code.


This post first appeared on Java Hungry, please read the originial post: here

Share the post

Print deck of cards in Java with Source Code

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×