简体   繁体   中英

Populate stack with deck of cards Java

I am currently designing a java application that will perform many different operations on a shuffled deck of cards. Within the application I have:

  • Stack.java: This is the interface for the program, including methods like pop,push, peek
  • Deck.java: My deck class, which implements stack
  • Card.java: Card object class
  • Shuffle.java: Contains the code to perform the riffle shuffle on the card
  • CardForce.java: Main class

The cards within my program can be described as having a face(A,2,3,4..J,K,Q) a suit(Hearts,Diamonds,Clubs,Spades) and a value which corresponds to the face ie
A = 1, 2 = 2, 3 = 3 and so on.

public Card(String cardFace, String cardSuit, int cardValue){
    face = cardFace;
    suit = cardSuit;
    value = cardValue;
}//ends Card

Currently I have my cards stored within an ArrayList within my deck class.

public class Deck implements Stack{


private List<Card> cards;

private int size;//number of cards in deck


public Deck(String[] faces, String[] suits, int[] values){
   cards = new ArrayList<Card>();
   for(String suit: suits) 
       for(int value = 0; value < values.length && value < faces.length; value++){
           Card a = new Card(faces[value], suit, values[value]);
           cards.add(a);
       }
   size = cards.size();
   //////////////////////////////////////shuffle();
   shuffle();
}//ends deck

I am looking to change my deck of cards from an arraylist to a stack, so I can perform the operations like pop, push & peek. Any help on how to implement those operations after the list has been converted to a stack is also welcome.

You can just add the stack functions to your Deck class and use the ArrayList as a stack. Something like this:

public void push(Card c) {
  cards.add(c);
}

public Card pop() {
  Card c = cards.get(cards.size() - 1);
  cards.remove(cards.size() - 1);
  return c;
}

public Card peek() {
  return cards.get(cards.size() - 1);
}

You will need to add checks to pop and peek to make sure there are actually Cards in your deck, but this pretty much covers it.

Just use the Stack class in the JDK it will support those capabilities.

You can populate a Stack with an arraylist.

      List<Card> list = your array list
      Stack<Card> stack = new Stack<>();
      stack.addAll(list);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM