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

血红的双手。 提交于 2019-12-02 12:26:24

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.

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