2

Hello Everyone

What I am trying to do is call the "FillDeck" method to fill the "deck []" with 52 array elements. The for loop is used to add the elements - for testing purposes it is just adding the y+x values from the for loop. What I did was use the variable "placement" to indicate my index position then increment the placement variable so for each loop iteration the index is increased thus adding an array element to that particular index. However, I get the IndexOutOfRangeException which is what I trying to figure out.

To note: I CANNOT automatically use predetermined values for the array, I must call a method which purpose is to add the values to the array. Since it is a card deck having a nested for loop to determine the rank / suit would be a good way to approach this.

Thanks =)

    static void Main(string[] args)
    {
        int [] deck = {};
        FillDeck(deck); // Error Here
    }
    public static void FillDeck(int[] deck)
    {
        int placement = 0;
        // 0 = Ace , 12 = King : 0 = Hearts, 1 = Diamonds, 2 = Clubs, 3 = Spades
        for (int x = 0; x < 13; x++)
            for (int y = 0; x < 4; ++y)
            {
                deck[placement] = x + y;// Error here
                ++placement;
            }

    }
JRoy
  • 25
  • 1
  • 1
  • 4
  • In addition to not instantiating your array to the correct size (52), your counter will only go up to 48. Your x counter is only going up to 12, not 13. – Stefan H May 30 '12 at 03:02

2 Answers2

5
int [] deck = {}

This creates an array of size 0.
You can't put anything in it.

You need to write new int[52] (or other appropriate number) to create an array that can actually hold things.

Alternatively, you can create a List<T>, which can expand to any (reasonable) size by calling the Add() method.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • That makes sense, I had a general idea that might have been an issue not indicating the array size. My programming skills are limited though and I have no idea about the List or the Add() method, how might I go about using them – JRoy May 30 '12 at 03:10
  • @JRoy List means a generic list of type T. So you could do: var deck = new List(); and then call deck.Add(x + y); – Stefan H May 30 '12 at 03:12
2

Of course error there, array inited size is 0 means no element you can store in it. hope code below can help you:

    public static int[] FillDeck()
    {
        var deck = new List<int>();
        // 0 = Ace , 12 = King : 0 = Hearts, 1 = Diamonds, 2 = Clubs, 3 = Spades
        for (int x = 0; x < 13; x++)
            for (int y = 0; x < 4; ++y)
            {
                deck.Add(x + y);
            }

        return deck.ToArray();

    }
kerryking
  • 104
  • 1
  • 6