错误:未处理的异常System.IndexOutofRangeException:索引超出了数组的范围

时间:2015-02-03 22:46:24

标签: c#

我还是c#的新手。直到最近,该代码一直运行数月而没有错误。它经常抛出错误:Unhandled Exception System.IndexOutofRangeException:Index超出了数组的范围。

我不确定代码中发生错误的位置。

private Random rnd = new Random();
string[] slots = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" };
private int slot1, slot2, slot3 = 0;

        if (message.Equals("!game"))
        {
            if (user == luckychance)
            {
                slot1 = 0;
                slot2 = 0;
                slot3 = rnd.Next(0, 6);
                luckychance = "";
            }
            else
            {
                slot1 = rnd.Next(0, 14);
                slot2 = rnd.Next(0, 14);
                slot3 = rnd.Next(0, 14);
            }
            if (slot1 == slot2 && slot1 == slot3)
            {
                sendMessage(slots[slot1] + " | " + slots[slot2] + " | " + slots[slot3] + " win", 2);
            }
            else
            {
                sendMessage(slots[slot1] + " | " + slots[slot2] + " | " + slots[slot3] + " lost", 2);
            }
        }

2 个答案:

答案 0 :(得分:2)

slot1 = rnd.Next(0, 14);

返回0..13

中的值

你只有13个“插槽”,但是从14个可能的插槽位置中挑选。

当插槽为13(您可能获得的最大值)时,您将尝试访问不存在的slots的第13个索引。

答案 1 :(得分:1)

你的插槽数组中有13个元素是零索引的,因此最大可能的索引是12.你指定一个小于14的随机值,所以当随机值大于12时,它超出了数组的边界