2013-03-10 86 views
0

我在执行我的代码时遇到问题,无法准确找出错误的来源或原因,也许有人可能会看一看,并在可能的情况下为我提供一些反馈。卡片经销商的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; 
} 
} 
+1

异常消息应该给你一个*堆栈跟踪*,即导致错误的嵌套调用序列。或者,您可以在调试器中运行代码,这将允许您在崩溃时检查变量值。 – 2013-03-10 17:52:58

+0

卡阵列中* card *的值大于数组中卡的总数。 ( - >这行返回卡[卡])你基本上试图返回第10张卡,而你只有9(例如) – Thousand 2013-03-10 17:54:11

+0

方面的建议:使用'enum'的西装。也许对于卡片的价值也是如此。 – 2013-03-10 17:55:51

回答

9

这个数组:

private static String[] suits = {"Clubs, Diamonds, Hearts, Spades"}; 

只包含一个项目 - 你可能是指:

private static String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"}; 
+1

哈哈,漂亮的接吻,找不到任何错误。 – 2013-03-10 17:53:31

+0

是的,很好的捕获 – chr 2013-03-10 17:55:07

+0

如果我整天都在那条线上出演,我可能不会捕捉到它。非常感谢,并且非常感谢。 – Masriyah 2013-03-10 17:57:24