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

泪湿孤枕 提交于 2019-12-02 16:48:33

问题


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 with created a switch table or if-else ladder assign the added value of the two cards as a variable score. The code below represents conceptually what I am trying to do, I just want to know how to make it simpler. Thanks!

    public int Score()
{
    int score = 0;

    if (card1.rank() == TWO && card2.rank() == TWO){
        score = 4;            
    } else if (card1.rank() == THREE && card2.rank() == TWO){
        score = 5;
    } else if (card1.rank() == FOUR && card2.rank() == TWO){
        score = 6;
    } else if (card1.rank() == FIVE && card2.rank() == TWO){
        score = 7;
    } else if (card1.rank() == SIX && card2.rank() == TWO){
        score = 8;
    } else if (card1.rank() == SEVEN && card2.rank() == TWO){
        score = 9;
    } else if (card1.rank() == EIGHT && card2.rank() == TWO){
        score = 10;
    } else if (card1.rank() == NINE && card2.rank() == TWO){
        score = 11;
    } else if (card1.rank() == TEN && card2.rank() == TWO){
        score = 12;

    return score;
}

The rank() method calls the integer value of the rank of each card, however, the card ranks are assigned in a different class as TWO = 0, THREE = 1, FOUR = 2... QUEEN = 10, KING = 11, ACE = 12 so I am trying to assign "score" to equal the actual value of the two cards, added together. Sorry if this is confusing I will answer any questions.


回答1:


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.



来源:https://stackoverflow.com/questions/26373409/how-to-add-the-values-of-two-cards-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!