我一直在尝试使用以下代码创建一副牌:
public DeckOfCards()
{
//constructor fills deck of Cards
String faces[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve" };
String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
deck = new Cards[ NUMBER_OF_CARDS ];
currentCard = 0;
randomNumbers = new Random();
//populate deck with Card objects
for( int count = 0; count < deck.length; count++ )
deck[ count ] =
new Cards( faces[ count % 13 ], suits[ count / 13 ] );
} //end DeckOfCard constructor
然而,有一个我无法解决的错误。它弹出这样: 线程“main”java.lang.ArrayIndexOutOfBoundsException中的异常:
for( int count = 0; count < deck.length; count++ )
deck[ count ] =
new Cards( faces[ count % 13 ], suits[ count / 13 ] );
为什么此错误会一直显示?任何帮助将不胜感激。
答案 0 :(得分:1)
您在faces[]
阵列中错过了一张卡片(十三张/一张王牌)。现在count % 13
会在返回12时给你an array out of bounds error
,因为你的数组只有12个元素[0-11]。向Thirteen
数组添加faces
或将模数值从13减少到12。