Instantly share code, notes, and snippets.

Embed
What would you like to do?
Deck of Cards Program With Methods
package chapter7;
public class DeckOfCards {
private static int[] initCardDeck() {
int[] deck = new int[52];
for (int i = 0; i < deck.length; i++)
deck[i] = i;
return deck;
}
private static void shuffleCards(int[] deck) {
for (int i = 0; i < deck.length; i++) {
int index = (int) (Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
}
private static int[] dealCards(int[] deck, int count) {
int[] hand = new int[count];
for (int i = 0; i < count; i++)
hand[i] = deck[i];
return hand;
}
private static void displayHand(int[] hand) {
final String[] suits = { "Spades", "Hearts", "Clubs", "Diamonds" };
final String[] ranks = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
for (int i = 0; i < hand.length; i++) {
String suit = suits[hand[i] / 13];
String rank = ranks[hand[i] % 13];
System.out.println("Card number " + hand[i] + ": " + rank + " of " + suit);
}
}
public static void main(String[] args) {
int[] deck = initCardDeck();
shuffleCards(deck);
int hand[] = dealCards(deck, 5);
displayHand(hand);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment