-3

当我创建一个类型的对象时Deck,会显示一个异常:“indexoutofrangeexception 未处理”

有人可以解释为什么吗?

public class Deck {
    Card[] card = new Card[52];
    const int NumOfCards = 52;

    public Deck()
    {
        string[] symbol = { "Diamonds", "Clubs", "Hearts", "Spades"};
        string[] rank = { "Ace", "Two", "Three", "Four", "Five", "Six", 
                          "Seven", "Eight", "Nine", "Jack", "Queen", "King"};

        for (int i = 0; i < card.Length; ++i)
        {
            /// this is the line with problem shown in debug                 
            card[i] = new Card(symbol[i / 13], rank[i % 13]);   
        }    
        Console.WriteLine(card.Length);
    }

    public void PrintDeck()  {
        foreach (Card c in card)
            Console.WriteLine(c);
    }
}
4

1 回答 1

-1

错误在行

card[i] = new Card(symbol[i / 13], rank[i % 13]);

在句子中

rank[i % 13]

i等于 12 时,我们得到 12 % 13 = 12,然后rank[12]是一个不存在的数组位置。要解决它,请 rank[i % 13] 更改 rank[i % 12]

于 2013-09-09T21:14:35.207 回答