我似乎與我的套牌項目出現錯誤。我想打印出的卡片洗牌甲板和我已經有了幫助,但這個錯誤現在已經停止從我的進展Java ArrayIndexOutOfBoundsException當試圖測試
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 51
\t at Pack.<init>(Pack.java:14)
\t 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
這裏是測試儀類。
public class PackTester {
public static void main(String[] args)
{
Pack myPack = new Pack();
myPack.shuffle();
System.out.println(myPack.toString());
}
}
我只是不知道從哪裏去,所以任何幫助,將不勝感激。
考慮使用列表並讓您的PlayingCard類實現Comparable接口,然後您可以通過調用Collections.shuffle(myCardList) – 2015-02-23 11:54:48