简体   繁体   中英

All cards are added to the same hand despite creating two different instances in Java

I'm creating a blackjack game in Java. I need to have multiple players and need a hand class to store the cards that have been pulled from the deck. I have a hand class that functions, but even when I create two separate hand instances, dealing a card to either hand adds them to both hands.

This is my hand class code:

public class Hand2 {
    
    private List<Cards> hand;
    private Cards cards;
    private int handValue;
    
    public Hand2(List<Cards> hand) {
        
        this.hand = hand;   
    }
    
    private Cards addCard(Deck deck) {
        hand.add(deck.dealCard());
        return cards;
    }
    
    public int getHandValue() {
        for (Cards cards : hand ) {
            handValue += cards.getValue();
        }
        return handValue;
    }

    public String toString() {
        return "Hand: " + hand;
    }

And below I am testing it:

public static void main(String[] args) { //Testing
     List<Cards> cards = new ArrayList<Cards>();
     
     Deck deck = new Deck();
        deck.shuffle();
                    
        Hand2 hand = new Hand2(cards);
        Hand2 hand2 = new Hand2(cards);
        
        hand.addCard(deck);
        hand2.addCard(deck);
        hand2.addCard(deck);
        System.out.println(hand2);
            System.out.println(hand.getHandValue());
        System.out.println(hand2.getHandValue());
   
 }  

Terminal:

Hand: [Three of Diamonds, Four of Clubs, Jack of Hearts]
17
17

But I get the same hand value for either hand.

As some have already noted, the same list of cards is shared between all hands. Another problem I see in you code is that you're using fields ( cards , handValue ) when you should use local variables.

Try this:

public class Hand2 {
    private final List<Cards> hand = new ArrayList<>();

    public Hand2() {
    }
    
    private Cards addCard(Deck deck) {
        Cards cards = deck.dealCard();
        hand.add(cards);
        return cards;
    }
    
    public int getHandValue() {
        int handValue = 0;
        for (Cards cards : hand ) {
            handValue += cards.getValue();
        }
        return handValue;
    }

    @Override
    public String toString() {
        return "Hand: " + hand;
    }

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