为什么这个数组超出范围?

时间:2014-01-28 21:16:03

标签: c# arrays indexoutofboundsexception

class Program
{
    static void Main(string[] args)
    {
        string[] deck = {"1♥","2♥","3♥","4♥","5♥","6♥","7♥","8♥","9♥","10♥","11♥","12♥","13♥",
                     "1♦","2♦","3♦","4♦","5♦","6♦","7♦","8♦","9♦","10♦","11♦","12♦","13♦",
                     "1♣","2♣","3♣","4♣","5♣","6♣","7♣","8♣","9♣","10♣","11♣","12♣","13♣",
                     "1♠","2♠","3♠","4♠","5♠","6♠","7♠","8♠","9♠","10♠","11♠","12♠","13♠"};

        string[] player = new string[26];
        string[] computer = new string[26];

        deck = Shuffle(deck);

        foreach (string d in deck)
        {
            Console.WriteLine(d);
        }

        Console.WriteLine(deck.Length);

        for (int i = 0; i < 26; i++)
        {
            player[i] = deck[i];
            Console.WriteLine(player[i]);
        }

        for (int j = 26; j < 52; j++)
        {
            computer[j] = deck[j];
            Console.WriteLine(computer[j]);
        }


    }

    static string[] Shuffle(string[] deck)
    {
        Random r = new Random();

        for (int i = deck.Length; i > 0; i--)
        {
            int j = r.Next(i);
            string k = deck[j];
            deck[j] = deck[i - 1];
            deck[i - 1] = k;
        }
        return deck;
    }

}

所以我尝试做的就是制作一副纸牌。然后我做的是使用Shuffle方法来改组阵列并更改甲板阵列。

它将甲板阵列的一半分配给播放器和计算机(播放器获得前半部计算机获得后半部分)。现在这是先洗牌所以是的,这似乎是公平的。

所以我得到一个越界错误的行是这一行:

computer[j] = deck[j];

5 个答案:

答案 0 :(得分:8)

您需要从0开始索引computer,而不是26:

for (int j = 26; j < 52; j++)
{
    computer[j - 26] = deck[j];
    Console.WriteLine(computer[j - 26]);
}

或者,偏移deck索引:

for (int i = 0; i < 26; i++)
{
    computer[i] = deck[i + 26];
    Console.WriteLine(computer[i]);
}

如果您不需要打印初始卡,您可以使用LINQ更简洁地实现这一点:

player = deck.Take(26).ToArray();
computer = deck.Skip(26).ToArray();

答案 1 :(得分:4)

您的计算机数组长度为26,因此最大索引为25.,但您尝试在该循环中向26.索引添加元素,即原因错误:

for (int j = 26; j < 52; j++)
{
     computer[j] = deck[j];
     Console.WriteLine(computer[j]);
}

此处的解决方案j减去26:

computer[j - 26] = deck[j];

也在那一行之后:

Console.WriteLine(computer[j-26]);

答案 2 :(得分:3)

应为computer[j-26] = deck[j];

答案 3 :(得分:2)

因为computer的长度只有26,所以j26开始,最多为52

索引26

时,您需要使用computer的偏移量
for (int j = 26; j < 52; j++)
{
    computer[j - 26] = deck[j];

    Console.WriteLine(computer[j]);
} 

答案 4 :(得分:2)

在你的循环中,deck的索引是正确的,因为它足够大。但是,computer只有26个元素。您的i从26开始,超出了computer的结尾。您需要为两个阵列调整一种方式或另一种方式,请参阅下面的

for (int j = 26; j < 52; j++)
{
    computer[j-26] = deck[j];
    //        ^ <-adjust for smaller array
    Console.WriteLine(computer[j]);
}