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

pur*_*ppc 0 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

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

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

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

computer[j] = deck[j];
Run Code Online (Sandbox Code Playgroud)

Dou*_*las 8

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

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

或者,抵消deck索引:

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

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

player = deck.Take(26).ToArray();
computer = deck.Skip(26).ToArray();
Run Code Online (Sandbox Code Playgroud)