How to add the values of two “Cards” in Java?

前端 未结 1 1200
野性不改
野性不改 2021-01-28 05:00

I am working on a project to simulate the first deal in a game of blackjack. So far, the program creates two cards of random rank (ACE to KING) and random suit. I am struggling

1条回答
  •  生来不讨喜
    2021-01-28 05:28

    Something like this:

    enum Rank {
        ACE(1),
        TWO(2),
        THREE(3),
        // ...
        TEN(10),
        JACK(10),
        QUEEN(10),
        KING(10);
    
        private final int value;
    
        Rank(int value) {
            this.value = value;
        }
        int getValue() {
            return this.value;
        }
    }
    
    // ...
    totalValue = card1.getRank().getValue() + card2.getRank().getValue();
    

    If you don't want to deal with enums, you can represent ranks as simple integers. It is less safe, but okay for simple and short code.

    But whichever representation you choose, you need to pay attention to aces - if you have an ace, there will be another sum that is 10 larger; if you have two, there will be an additional sum that is 20 larger.

    0 讨论(0)
提交回复
热议问题