猿问

计算 cardSum (Hands of Strings)

我正在尝试创建一个二十一点游戏。游戏本身非常简单(至少是我的版本)。玩家从洗好的一副牌中抽出一张牌,并计算已抽出的牌的总和。我有一个字符串类型的卡片组列表,这对我来说现在是一个大问题。我不知道如何计算总和,因为它们是字符串类型。你对我能做什么有什么指导方针吗?我想出的唯一解决方案真的很糟糕,就是将卡片与字符串进行比较并给它一个值。例如,drawnCard.equals("Four of hearts") = "4";


    public class Player {



    private String nickName;

    private int playerNumOfCards;

    ArrayList<Card> playerHand = new ArrayList<>();



    public Player (String name){

        this.nickName = name;

    }


    public String getNickName() {

        return nickName;

    }


    public void addCard(Card aCard){

        playerHand.add(aCard);

        this.playerNumOfCards++;


    }


    public void getHandSum(){


    }


    public void getPlayerHand(){

        for(Card cards: playerHand){

            System.out.println(cards.toString());

        }

    }



  }


白板的微信
浏览 132回答 2
2回答

守着星空守着你

创建一个枚举来表示 Faceenum Face {&nbsp; &nbsp; Ace(number), //I don't know what number is for Ace and others.&nbsp; &nbsp; Deuce(number),&nbsp; &nbsp; Three(3),&nbsp; &nbsp; Four(4),&nbsp; &nbsp; Five(5),&nbsp; &nbsp; Six(6),&nbsp; &nbsp; Seven(7),&nbsp; &nbsp; Eight(8),&nbsp; &nbsp; Nine(9),&nbsp; &nbsp; Ten(10),&nbsp; &nbsp; Jack(number),&nbsp; &nbsp; Queen(number),&nbsp; &nbsp; King(number);&nbsp; &nbsp; private final int number;&nbsp; &nbsp; Faces(int number) {&nbsp; &nbsp; &nbsp; &nbsp; this.number = number;&nbsp; &nbsp; }&nbsp; &nbsp; public int getNumber() {&nbsp; &nbsp; &nbsp; &nbsp; return number;&nbsp; &nbsp; }}将面的类型从字符串更改为面。class Card {&nbsp; &nbsp; private Face face;&nbsp; &nbsp; private String suit;&nbsp; &nbsp; public Card (Face cardFace, String cardSuit){card's face and suit&nbsp; &nbsp; &nbsp; &nbsp; this.face = cardFace;&nbsp; &nbsp; &nbsp; &nbsp; this.suit = cardSuit;&nbsp; &nbsp; }&nbsp; &nbsp; public String toString(){&nbsp; &nbsp; &nbsp; &nbsp; return face + " of " + suit;&nbsp; &nbsp; }&nbsp; &nbsp; public int getNumber() {&nbsp; &nbsp; &nbsp; &nbsp; return face.getNumber();&nbsp; &nbsp; }}添加一个从卡片类中获取人脸号码的方法,然后相应地使用它。您还需要更改其他部分或您的项目,但我会将其留给您。还建议对 Suit 使用 enum。

撒科打诨

我在那里看不到牌组列表,但是如果您的卡片字符串始终遵循相同的命名约定(即“四颗心”),您可以通过将每个字符串按“字符串中获取数字的第一个单词(或对应的 10 表示国王/王后等。)&nbsp;String cardName = "four of hearts" (or whatever the variable name is);&nbsp; &nbsp;String[] parts = string.split(" ");&nbsp; &nbsp;String number = parts[0];因此数字将仅等于“四”,而不必比较“四颗心”以返回数字 4。希望有帮助
随时随地看视频慕课网APP

相关分类

Java
我要回答