Cedric Della faille
Cedric Della faille

Reputation: 15

using Switch in for loop

I have already received this problem a few times, i wonder why i can't use my index in the switch, i receive an error that the array[index] = null, any reason why?

// array of classes, im using public getters and setters to access the rank and cardcolor
Cardgame[] cardgame = new Cardgame[50];
int index = 0;
string CardColor = "";

...             

for (int i = 0; i < 4; i++)
{
    switch (i)
    {
        case 1: CardColor = "red";
            break;
        case 2: CardColor = "blue";
            break;
        case 3: CardColor = "diamond";
            break;
        case 4: CardColor = "candy!";
            break;
    }
    for (int x = 0; x <= 13; x++)
    {
        index++; 
     Cardgame[index].Color = CardColor;
        switch (x)
        {

            default: Cardgame[index].Number = x.ToString();
                break;
            case 11: Cardgame[index].Number = "Farmer";

                break;
            case 12: Cardgame[index].Number = "Queen";

                break;
            case 13: Cardgame[index].Number = "King";

                break;
        }
    }

Upvotes: 0

Views: 141

Answers (3)

Austin Salonen
Austin Salonen

Reputation: 50215

// first define the possible values
var suits = new [] {"red", "blue", "diamond", "candy"};
var ranks = new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "farmer", "queen", "king"}

//var ranks = Enumerable.Range(1, 10).Select(n => n.ToString())
//                      .Concat(new [] {"farmer", "queen", "king"})
//                      .ToArray();

// given the known values, you just iterate over every possible index
for(int i = 0; i < suits.Length * ranks.Length; i++)
{
    Cardgame[i] = new CardGame();
    Cardgame[i].CardColor = suits[i % suits.Length];
    Cardgame[i].Number = ranks[i / ranks.Length];
}

// or some "harder" LINQ    
var Cardgame = (from s in suits
               from r in ranks
               select new CardGame(s, r)).ToArray();

Upvotes: 1

alanmanderson
alanmanderson

Reputation: 8200

You are iterating through the first loop 5 times and iterating through 14 cards each time... That is 70 cards.

Also, you are never initializing any of the cardgame objects.

you want to do:

for (int i = 0; i < 4; i++)
{
    ...
    for (int x = 0; x < 13; x++)
    {
        Cardgame[index] = new Cardgame();            
        ...
        index++;
    }
    ...
}

Upvotes: 0

ChrisWue
ChrisWue

Reputation: 19020

Because you have an array of Cardgame objects. The default array initializer will set all objects to null. You have to do a cardgame[index] = new Cardgame() first.

Upvotes: 3

Related Questions