Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

When I create an object of type Deck, an exception is shown: "indexoutofrangeexception was unhandled"

Can someone explain why?

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);
    }
}
share|improve this question
3  
Check the i % 13 value, then count items in rank, then look for "Ten" –  zerkms Sep 9 '13 at 21:01
    
Pff Zerk, I feel bad for posting as an answer now :) –  Rawling Sep 9 '13 at 21:03
1  
@Rawling: put en.wikipedia.org/wiki/Off-by-one_error there and it will be fine :-) –  zerkms Sep 9 '13 at 21:03
1  
why the close vote? this is very good question for SO. –  Preet Sangha Sep 9 '13 at 21:05
    
symbol has an off-by-nine error. I wonder why the OP uses card.Length, but not symbol.Length and rank.Length. –  dcaswell Sep 9 '13 at 21:14

1 Answer 1

up vote -1 down vote accepted

The error is in line

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

In the sentence

rank[i % 13]

when i is equal to 12, we got 12 % 13 = 12, and then rank[12] is an array position that not exists. To solve it, change rank[i % 13] by rank[i % 12]

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.