|
| 1 | +package ArraysAndStrings; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +public class Deck { |
| 6 | + |
| 7 | + private String[] SUITS; |
| 8 | + private String[] RANKS; |
| 9 | + private String[] DECK; |
| 10 | + private int numOfCards; |
| 11 | + |
| 12 | + public Deck(){ |
| 13 | + this.SUITS = new String[] { |
| 14 | + "Clubs","Diamonds","Hearts","Spades" |
| 15 | + }; |
| 16 | + |
| 17 | + this.RANKS = new String[] { |
| 18 | + "2","3","4","5","6","7","8","9", |
| 19 | + "Jack","Queen","King","Ace" |
| 20 | + }; |
| 21 | + |
| 22 | + //initalize the deck |
| 23 | + numOfCards = SUITS.length * RANKS.length; |
| 24 | + DECK = new String[numOfCards]; |
| 25 | + |
| 26 | + for(int i=0; i<RANKS.length; i++){ |
| 27 | + for(int j=0; j<SUITS.length; j++) { |
| 28 | + DECK[SUITS.length*i +j] = RANKS[i] + " of " + SUITS[j]; |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + //shuffle deck |
| 34 | + public void shuffleDeck() { |
| 35 | + for (int i=0; i<numOfCards; i++) { |
| 36 | + int rand = i + (int) (Math.random() * (numOfCards-i)); |
| 37 | + |
| 38 | + //swap |
| 39 | + String temp = DECK[rand]; |
| 40 | + DECK[rand] = DECK[i]; |
| 41 | + DECK[i] = temp; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + //print deck |
| 46 | + public void printDeck() { |
| 47 | + for (int i =0; i< numOfCards; i++) |
| 48 | + System.out.println(DECK[i]); |
| 49 | + } |
| 50 | + |
| 51 | + public static void main(String[] args) { |
| 52 | + Deck deck = new Deck(); |
| 53 | + deck.printDeck(); |
| 54 | + deck.shuffleDeck(); |
| 55 | + deck.printDeck(); |
| 56 | + } |
| 57 | +} |
0 commit comments