-6

它不断抛出这个异常,但它显示在程序的输出之间,到目前为止,它完全按照我的需要运行。可能是什么问题?

好吧,这就是它引发异常的地方: public class RunGame {

public static void main(String[] args) {
    //Create players
    Hand Player1 = new Hand(5);
    Hand Player2 = new Hand(5);
    Hand Player3 = new Hand(5);
    Hand Player4 = new Hand(5);

    Deck deck = new Deck();
    Card print = new Card(1,'c');

    deck.Shuffle();
    for (int i = 0; i <= 52; i++){
        print = deck.getCard(i); //**THROWS HERE**
        System.out.println(print.toString());
    }    

然后在我的甲板课上有:

public class Deck {
private char suit;
private int value;
private Card [] deck = new Card[52];

public Deck(){ 

    int count = 0;
    for(int i = 1; i <= 4; i++) {
        if (i == 1)
        {
            suit = 'C';
        }
        else if (i == 2) {
            suit = 'D';
        }
        else if (i == 3)  {
            suit = 'H';
        }
        else {
            suit = 'S';
        }
        for (int x = 1; x <= 13; x++){
            deck[count] = new Card(x, suit);
            count++;
        }
    }
}

public Card getCard(int i){
    int v = deck[i].getValue(); //**AND HERE**
    char s = deck[i].getSuit();
    Card temp = new Card(v,s);
    return temp;
}

我只是想打印甲板以确保它正确洗牌。一切都打印得很好,但它仍然表明了这一点。(我的卡片组对象是一个 52 张卡片的数组,getValue 和 getCard 方法在 Card 类中。)

4

2 回答 2

1

我猜你的循环中的 deck.getCard(i) 有时会返回 null,然后当你尝试从该 null 引用调用 toString() 时,程序会崩溃。

也许你的循环应该说 i < 52 而不是 <=? 不过,这应该会导致 ArrayIndexOutOfBoundsException。如果没有看到整个 Deck 类,真的很难说。

于 2013-10-15T23:27:56.557 回答
1

你有 52 张卡片。
如果您从 0 开始计数(正确),您将在第 51 次到达第 52 卡。
您数到并包括 52;这是不正确的,因为元素 0 需要包含在计数中。
一个简单的错误。

将代码更改为:

for (int i = 0; i < 52; i++){
    print = deck.getCard(i); //No more exception
于 2013-10-15T23:29:49.143 回答