混乱和数组问题Java

时间:2016-10-06 19:50:42

标签: java

我的Java程序Black Jack出了问题。我似乎无法解决我的“this.cards [o ++]”,因为它总是进入ArrayIndexOutOfBoundException。但是,如果我将其更改为“this.cards [j]或this.cards [i]”,它不会出错,但我知道它错了。

以下是错误:

**this.cards[o++]** 
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
        at CardDeck.<init>(CardDeck.java:18)
        at BlackJoker.main(BlackJoker.java:17)

**this.cards[j]**
null
Kc
Qc
8c
null
null

**this.cards[i]**
null
Ac
Ah
null
null
Ad

这是我的代码:

import java.util.*;
public class CardDeck
{
    private String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10",
                    "J", "Q", "K", "A" };
    private char[] suits = {'s','h','d','c'};
    private Card[] cards = new Card[13];
    private int currentCard;

    CardDeck()
    {
        Card newCard;
        int o = 0;
        for(int i=0; i<this.suits.length; i++)
        {   
            for(int j=0; j<this.ranks.length; j++)
            {
                this.cards[o++] = new Card(this.ranks[j], this.suits[i]);
            }
        }
        this.shuffle();
    }

    public void testing() //just for testing 
    {
        System.out.println(this.suits[0]);
    }   

    public Card drawNextCard()
    {

        return cards[currentCard++];
    }

    private void shuffle()
    {
        Card[] tmp = new Card[13];
        for (int i = 0; i < cards.length; i++)
        {
            int index = (int)(Math.random() * (cards.length));

            tmp[index] = cards[i];
            cards[i] = cards[index];
            cards[index] = tmp[i];
        } 
    }
}
public class BlackJoker
{
    public static void main(String[] args)
    {
        CardDeck cardDeck = new CardDeck();

        //cardDeck.testing();
        System.out.println(cardDeck.drawNextCard());
        System.out.println(cardDeck.drawNextCard());
        System.out.println(cardDeck.drawNextCard());
        System.out.println(cardDeck.drawNextCard());
        System.out.println(cardDeck.drawNextCard());
        System.out.println(cardDeck.drawNextCard());
        //System.out.println(cardDeck.drawNextCard());
    }
}

2 个答案:

答案 0 :(得分:1)

您正在分配一个只能容纳13张牌的阵列:

private Card[] cards = new Card[13];

尝试制作52:

private Card[] cards = new Card[52];

答案 1 :(得分:0)

除了增加卡片阵列长度之外,在shuffle函数中,您使用Math.random计算索引,如果索引超出卡片阵列长度,则会导致ArrayIndexOutbound异常。你需要处理这个问题。