我在執行我的代碼時遇到問題,無法準確找出錯誤的來源或原因,也許有人可能會看一看,並在可能的情況下爲我提供一些反饋。卡片經銷商的Java模擬 - ArrayIndexOutOfBoundsException
錯誤消息:
51
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
3 of Clubs, Diamonds, Hearts, Spades
at javacards.Card.toString(Card.java:15)
at javacards.CardRun.main(CardRun.java:15)
CardRun類別:
public class CardRun {
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 card, suit;
private static String[] suits = {"Clubs, Diamonds, Hearts, Spades"};
private static String[] cards = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
Card(int suit, int card)
{
this.card = card;
this.suit = suit;
}
public @Override String toString()
{
return cards[card] + " of " + suits[suit];
}
public int getCard()
{
return card;
}
public int getSuit()
{
return suit;
}
}
甲板類
public class Deck {
private Card[]cards;
int i;
Deck()
{
i = 51;
cards = new Card[52];
int x = 0;
for(int a=0; a<=3; a++)
{
for(int b=0; b<=12; b++)
{
cards[x] = new Card(a,b);
x++;
}
}
}
public Card drawFromDeck()
{
Random generator = new Random();
int index = 0;
index = generator.nextInt(i);
Card temp = cards[index];
cards[index] = cards[i];
cards[i] = null;
i--;
return temp;
}
public int getTotalCards()
{
return i;
}
}
異常消息應該給你一個*堆棧跟蹤*,即導致錯誤的嵌套調用序列。或者,您可以在調試器中運行代碼,這將允許您在崩潰時檢查變量值。 – 2013-03-10 17:52:58
卡陣列中* card *的值大於數組中卡的總數。 ( - >這行返回卡[卡])你基本上試圖返回第10張卡,而你只有9(例如) – Thousand 2013-03-10 17:54:11
方面的建議:使用'enum'的西裝。也許對於卡片的價值也是如此。 – 2013-03-10 17:55:51