数组的百家乐游戏在几轮后引发异常

问题描述 投票:0回答:1

我几乎已经完成了比赛,但我不确定为什么它会在几轮后下降。我认为它与甲板课的编写方式有关。它由老师提供,但我可能需要修复它。

我想也许在几轮后,阵列变得太满或什么的,所以我尝试添加一种方法来清除它们。这不起作用,我不认为这是问题,但我不确定。


class deck{

    private String [] cards = {"A","K","Q","J","10","9","8","7","6","5","4","3","2"};
    private int cardCount = 1;
    private boolean isShuffled = false;

    //**********Shuffle cards method****************************
    private void shuffleCards(){//shuffle cards method

        for (int i = 0; i < cards.length; i++) {
            int index = (int)(Math.random() * 13);
            String temp = cards[i];
            cards[i] = cards[index];
            cards[index] = temp;
        }
        isShuffled = true;
    }

    //********Ensure the cards get shuffled before dealing******
    public String getCards(){

        if (isShuffled == true){
            cardCount++;
            return cards[cardCount];
        }
        else {
            shuffleCards();//shuffle if they have not
            cardCount++;
            return cards[cardCount];
        }
    }

    //********Show cards method*********************************
    public void showCards(String [] theirCards){

        for (int i = 0; i < theirCards.length; i++) {
            if(theirCards[i] == null){
                continue;
            }
            System.out.print(theirCards[i] + " ");
        }
    }

    public void clearCards(){
        cards = null;
        cards = null;
    }

    //*******Card value method**********************************
    public int getCardValues(String tempChar){

        int indValues = 1;

        switch (tempChar){
            case "A": indValues = 1; break;
             blah blah blah
            case "3": indValues = 3; break;
            case "2": indValues = 2;

        }
        return indValues;
    }
}

我希望游戏能够保持循环,直到我通过投注退出或用完资金,但相反,在大约3场比赛后,我收到此错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
    at deck.getCards(Baccarat.java:248)
    at playerObjects.setComputersCards(Baccarat.java:177)
    at Baccarat.main(Baccarat.java:19)
java arrays indexoutofboundsexception
1个回答
0
投票

两个明显的问题:

首先,cardCount初始化为1(如前所述)。其次,在方法getCards()中,cardCount在返回卡之前递增。要解决此问题,您应该将cardCount初始化为-1而不是1。

就像现在一样,你总是跳过你牌组中的前两张牌,所以你只有11张牌,而不是你所假设的13张牌,这可能就是为什么你在第三轮比赛中超过指数 - 百家乐牌对于玩家和银行来说,通常都是2到3张牌,这样就可以加起来。

首先,您应该将cardCount初始化为-1。其次,作为故障保护,你应该修改getCards()方法来测试你的cardCount,如果是12,则考虑将其设置为-1并在执行增量/返回卡之前再次洗牌。换句话说,让套牌管理自己以避免索引超出范围。

© www.soinside.com 2019 - 2024. All rights reserved.