Java 尝试测试时出现 ArrayIndexOutOfBoundsException

Java ArrayIndexOutOfBoundsException When Trying to Test

我的扑克牌项目似乎出错了。我正在尝试打印一副洗好的纸牌,我已经得到了帮助,但这个错误现在阻止了我的进步

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 51
 at Pack.<init>(Pack.java:14)
 at PackTester.main(PackTester.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)

  public class Pack {

private PlayingCard[] deck;   // An array of 52 cards, representing the deck.
private int cardsUsed; // How many cards have been dealt from the deck.

/**
* Creating an unshuffled deck of cards
*/
public Pack() {
   deck = new PlayingCard[51]; //Creates an array of 52 playing cards
   int cardCt = 0; // How many cards have been created so far.
   for ( int suit = 0; suit <= 3; suit++ ) { //If a suit is complete, move to the next suit
      for ( int rank = 1; rank <= 14; rank++ ) { //Builds a complete suit
         deck[51] = new PlayingCard(rank, suit);
         cardCt++; //Adds one to the card count
      }
   }
   cardCt = 0;
}

/**
* Shuffling a deck of cards
*/
public void shuffle() {
      // Put all the used cards back into the deck, and shuffle it into
      // a random order.
    for ( int i = 51; i > 0; i-- ) { 
        int rand = (int)(Math.random()*(i+1));
        PlayingCard temp = deck[i];
        deck[i] = deck[rand];
        deck[rand] = temp;
    }
    cardsUsed = 0;
}

public @Override String toString() {

String deckStr = "";

for (int i=0; i<52; i++) {
    deckStr = deckStr + deck[i].toString() + " ";
}

return deckStr;
}
} // end class Pack

这里是测试人员 class。

public class PackTester {

public static void main(String[] args)
{
    Pack myPack = new Pack();
    myPack.shuffle();
    System.out.println(myPack.toString());
}
}

我只是不知道从这里去哪里,所以任何帮助将不胜感激。

为了创建一副包含 52 张卡片的牌组,您需要:

deck = new PlayingCard[52];

此外,您的循环总是将卡片分配到第 51 个位置毫无意义:

deck[51] = new PlayingCard(rank, suit);

这样更有意义:

public Pack() {
   deck = new PlayingCard[52]; //Creates an array of 52 playing cards
   int cardCt = 0; // How many cards have been created so far.
   for ( int suit = 0; suit <= 3; suit++ ) { //If a suit is complete, move to the next suit
      for ( int rank = 1; rank < 14; rank++ ) { //Builds a complete suit
         deck[cardCt] = new PlayingCard(rank, suit);
         cardCt++; //Adds one to the card count
      }
   }
}

另请注意,应该有 13 个等级,而不是 14 个。

您将数组定义为:

deck = new PlayingCard[51];

而您正在尝试添加如下元素:

deck[51] = new PlayingCard(rank, suit);

您正在尝试设置数组中的第 51 个索引元素。

同样在随机播放方法中:

for ( int i = 51; i > 0; i-- ) { //either start with 50 or define array as PlayingCard[52]
int rand = (int)(Math.random()*(i+1));
 PlayingCard temp = deck[i];

记住数组的索引从 0 开始一直上升到 n -1,所以你需要第 52 个元素(52 张卡片,即第 52 个将由索引 51 访问),当你将数组容量从 51 增加到 52定义数组。