在C#中创建循环对象数组?

时间:2013-09-09 21:00:49

标签: c# arrays

当我创建类型为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);
    }
}

1 个答案:

答案 0 :(得分:-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]