卡片经销商的java模拟 - ArrayIndexOutOfBoundsException

时间:2013-03-10 17:50:37

标签: java

我在执行代码时遇到问题,无法确切地指出错误的来源或原因,也许有人可能会看一看并在可能的情况下向我提供一些反馈。

错误讯息:

51
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
3 of Clubs, Diamonds, Hearts, Spades
    at javacards.Card.toString(Card.java:15)
    at javacards.CardRun.main(CardRun.java:15)

CardRun课程:

public class CardRun {

public static void main(String[] args)
{
    Deck deck = new Deck();
    Card C;

    System.out.println(deck.getTotalCards());

    while(deck.getTotalCards() != 0)
    {
        C = deck.drawFromDeck();
        System.out.println(C.toString());
    }
}

卡类

public class Card {
    private int card, suit;
    private static String[] suits = {"Clubs, Diamonds, Hearts, Spades"};
    private static String[] cards = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

    Card(int suit, int card)
    {
        this.card = card;
        this.suit = suit;
    }

    public @Override String toString()
    {
        return cards[card] + " of " + suits[suit];
    }

    public int getCard()
    {
        return card;
    }

    public int getSuit()
    {
        return suit;
    }
}

甲板上课

public class Deck {

private Card[]cards;
int i;

Deck()
{
    i = 51; 
    cards = new Card[52];
    int x = 0;
    for(int a=0; a<=3; a++)
    {
        for(int b=0; b<=12; b++)
        {
            cards[x] = new Card(a,b);
            x++;
        }
    }
}

public Card drawFromDeck()
{
    Random generator = new Random();
    int index = 0;

    index = generator.nextInt(i);
    Card temp = cards[index];
    cards[index] = cards[i];
    cards[i] = null;
    i--;
    return temp;
}

public int getTotalCards()
{
    return i;
}
}

1 个答案:

答案 0 :(得分:9)

这个数组:

private static String[] suits = {"Clubs, Diamonds, Hearts, Spades"};

只包含一个项目 - 您可能意味着:

private static String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};