Need some assistance on this program I'm working on. Basically a card draw program that creates a deck of cards (card and deck classes), shuffles the created deck, and adds the first card of the shuffled deck to the player's hand. (CardPlayer class).
package cards;
public class Card {
private String[]cardSuit = {"Hearts", "Diamonds", "Spades", "Clubs"};
private String[]cardFaceValue = {"Ace", "King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2"};
private int suit;
private int faceValue;
public Card(int newSuit, int newValue) {
suit = newSuit;
faceValue = newValue;
}
public String toString() {
String card = cardFaceValue[faceValue] " of " cardSuit[suit];
return card;
}
}
package cards;
import java.util.*;
public class Deck {
ArrayList<Card> deck = new ArrayList<>();
public Deck() {
for(int suit = 0; suit <= 3; suit ) {
for(int value = 0; value <= 12; value ) {
deck.add(new Card(suit,value));
}
}
}
public void Shuffle() {
Collections.shuffle(deck);
}
public Card Deal() {
Card card = deck.get(0);
deck.remove(0);
return card;
}
}
package cards;
import java.util.*;
public class CardPlayer {
Deck deck = new Deck();
ArrayList<Card> hand = new ArrayList<>();
public void getCard(){
hand.add(deck.Deal());
}
public ArrayList<Card> showCards(){
return hand;
}
}
package cards;
public class Demonstration {
public static void main(String[] args) {
Deck deck;
deck = new Deck();
CardPlayer cardPlayer;
cardPlayer = new CardPlayer();
System.out.println("The deck contains the cards: " deck.deck);
deck.Shuffle();
System.out.println("New order of cards: " deck.deck);
cardPlayer.getCard();
cardPlayer.getCard();
cardPlayer.getCard();
cardPlayer.getCard();
cardPlayer.getCard();
System.out.println("The card player's hand is now: " cardPlayer.showCards());
}
}
My issue is that whenever I run the demonstration program, the deck and shuffle work, but when I try to show the cards in the player's hand, it's always the same cards in the order created by the initial deck creation, without the shuffle. How would I go about fixing this issue?
CodePudding user response:
You are having two instances of Deck
class - one in the main method and one in the CardPlayer
class. The one in the CardPlayer
class is used in getCard
but that deck isn't shuffled.
Either shuffle the deck created in CardPlayer
class. Or pass the shuffled deck created in main to the constructor of the CardPlayer
class.