Write a JAVA program to simulate a deck of cards with some b
Write a JAVA program to simulate a deck of cards with some basic functionality. The easiest way to do this is to break it up into classes for a Card, a Stack, a Deck, and then a main class to demonstrate that the operations work successfully. A Card will have a suit and a value and it should include a toString() method which displays cards like “Queen of Hearts” or “Two of Spades.” You can do this however you’d like. You may want to look up how to use an enum if you have never used them before. A Stack can be implemented using an ArrayList or a LinkedList and must include methods such as pop, push, peek, and isEmpty. A Deck uses the methods available through the Stack. It should allow you to create a new Deck of 52 cards, shuffle those cards, and then deal some number.
Solution
Card.java
public class Card{
String cardNumber;
String suit;
public Card(String cardNumber, String suit){
this.cardNumber = cardNumber;
this.suit = suit;
}
public String toString(){
return cardNumber + \" of \" + suit;
}
}
Enums.java
public class Enums{
public enum cardNumber{
Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
};
public enum suit{
Hearts, Spades, Clubs, Diamonds
};
}
Stack.java
import java.util.ArrayList;
import java.util.EmptyStackException;
public class Stack {
private ArrayList<Card> stack = new ArrayList<Card>();
public void push(Card card) {
// Add obj to the stack.
stack.add(card);
}
public Card pop() {
// Return and remove the top item from
// the stack. Throws an EmptyStackException
// if there are no elements on the stack.
if (stack.isEmpty())
throw new EmptyStackException();
return stack.remove(stack.size()-1);
}
public boolean isEmpty() {
// Test whether the stack is empty.
return stack.isEmpty();
}
}
Deck.java
import java.util.ArrayList;
import java.util.Collections;
public class Deck{
public Stack deck;
public Deck(){
deck = new Stack();
ArrayList<Card> cardsList = new ArrayList<Card>();
for (int i=0; i<Enums.suit.values().length; i++){
for (int j=0; j<Enums.cardNumber.values().length; j++){
cardsList.add(new Card(Enums.cardNumber.values()[j].toString(), Enums.suit.values()[i].toString()));
}
}
Collections.shuffle(cardsList);
for (Card card: cardsList){
deck.push(card);
}
}
}
MainClass.java
public class MainClass{
public static void main(String[] args) {
Deck deck = new Deck();
System.out.println(deck.deck.pop());
}
}

