为什么我在这个程序中遇到“ArrayIndexOutOfBounds”错误?

时间:2015-06-24 12:21:20

标签: java arrays playing-cards

我写了这个程序来初始化并创建一副牌,将其洗牌,然后交出N手牌。尽管编译每次都顺利进行,但当我运行程序时,它会抛出一个不同的ArrayIndexOutOfBounds(:52或:54)。我通过使用System.out.println(1),更改和交换索引,更改了数组的长度等来检查错误。但我很难过......也许你可以帮助我?

public class Deal 
{

public static void main(String[] args) 
{ 

    int N = Integer.parseInt(args[0]);
    int hand = 5;

    String[] rank = 
    {
        "2", "3", "4", "5", "6", "7", "8", "9", "10", 
        "Jack", "Queen", "King", "Ace"
    };

    String[] suit = {"Spades", "Hearts", "Clubs", "Diamonds"};

    // Create Deck
    String[] deck = new String[rank.length * suit.length];

    // Fill the deck with cards
    for (int i = 0; i < suit.length; i++)
    {
        for (int j = 0; j < rank.length; j++)
        {
            //System.out.println(1);
            deck[rank.length*i + j] = rank[j] + " of " + suit[i];
            System.out.println(deck[rank.length*i +j]);
        }
    }

    // Shuffle deck
    for (int i = 0; i < deck.length; i++)
    {
        int r = i + (int)(Math.random() * (N-1));
        String t = deck[i];
        deck[i] = deck[r];
        deck[r] = t;
    }

    // Count number of cards dealt
    int counter = 0;

    while (N != 0 && counter <= deck.length)
    {
        for (int i = counter; i < hand + counter; i++)
        {
            System.out.println(deck[i]);
            counter++;
        }

        N--;
        System.out.println();
    }
}
}

1 个答案:

答案 0 :(得分:3)

问题在于你的洗牌代码:

for (int i = 0; i < deck.length; i++)
{
    int r = i + (int)(Math.random() * (N-1));
    String t = deck[i];
    deck[i] = deck[r];
    deck[r] = t;
}

无法保证r将在范围内 - 只要i在最后N内,它就会失败,具体取决于生成的随机数。

更好:使用Collections.shuffle

Collections.shuffle(Arrays.asList(deck));

当您修复此问题后,您然后会遇到问题:

while (N != 0 && counter <= deck.length)
{
    for (int i = counter; i < hand + counter; i++)
    {
        System.out.println(deck[i]);

counter == deck.length时,您期望发生什么?

基本上,所有问题的答案都涉及以下步骤:

  • 找出代码失败的
  • 了解如何/为何获得无效索引
  • 找出实际想要做的事情,以便保持在数组的范围内
  • 实施更改