卡片索引/数组错误

时间:2014-02-26 17:42:53

标签: java arrays indexing

我正在尝试创建一副自动洗牌的卡片,然后以随机顺序输出卡片。我遇到错误ArrayIndexOutOfBoundsException的行

return ranks[rank] + " of " + suits[suit];

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

我做错了什么?它输出卡座尺寸,然后在显示错误代码之前偶尔输出一两张卡片。提前谢谢。

import java.util.Random;
import java.util.ArrayList;

public class Deck
    {
    private ArrayList<Card> cards;

    Deck()
        {
        cards = new ArrayList<Card>();
        for (int a=0; a<=3; a++)
            {
            for (int b=0; b<=12; b++)
                {
                cards.add( new Card(a,b) );
                }
            }
        }

    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 rank,
                    suit;

        private String[] suits = {"Hearts", "Spades", "Diamonds", "Clubs"};
        private String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

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

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

        public int getRank()
            {
            return rank;
            }

        public int getSuit()
            {
            return suit;
            }
        }

    public Card drawFromDeck()
        {
        Random generator = new Random();
        int index = generator.nextInt( cards.size() );
        return cards.remove(index);
        }


    public int getTotalCards()
        {
        return cards.size();
        }
    }

1 个答案:

答案 0 :(得分:0)

那里的一切都很好但你会向后初始化卡片。 您的Card构造函数为(rank, suit),而您的Deck构造函数正在创建(suit, rank)

只需在第15行的Deck构造函数中翻转args的顺序

cards.add( new Card(a, b) );

应该是

cards.add( new Card(b, a) );

由于a的范围是0到3,asuit,应该是构造函数中的第二个参数。