【问题标题】:Error: Unhandled Exception System.IndexOutofRangeException: Index was outside the bounds of the array错误:未处理的异常 System.IndexOutofRangeException:索引超出了数组的范围
【发布时间】:2015-02-03 22:46:24
【问题描述】:

我还是 C# 的新手。直到最近,该代码已经运行了几个月而没有出现错误。它不断地抛出错误:Unhandled Exception System.IndexOutofRangeException: Index was outside the bounds of the array。

我不确定代码中的错误发生在哪里。

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);
            }
        }

【问题讨论】:

  • 哪一行报错?
  • 假设您使用rnd.Next 调用的结果(如果不是,则提示),请仔细阅读文档。
  • 此代码在接收消息的地方还有更多内容,并且该部分会引发数组错误。通常发生这种情况时,它与消息调用的函数有关。
  • @PrestonGuillot:Next 的上限是独占,但仍高出一个(从零开始的数组)。
  • 您可能已经忘记了您的数组实际上是 0 索引的,即使您从“1”开始您的数组。

标签: c#


【解决方案1】:
slot1 = rnd.Next(0, 14);

从 0..13 返回一个值

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

当一个 slot 为 13(你可能得到的最大值)时,你将尝试访问不存在的 slots 的第 13 个索引。

【讨论】:

  • 有人告诉我 Next (0, 14),其中 14 是最大界限,不包括在内。我错了吗?谢谢你。也许我对 0 感到困惑。
  • 14 不包括在内,但 13 也太大了。您的数组具有从 0 到 12 的索引(请记住,C# 中的数组是从零开始的。第一个元素是 slots[0]。
  • 非常感谢,现在更有意义了。
【解决方案2】:

您的插槽数组中有 13 个元素,索引为零,因此最大可能索引为 12。您分配的随机值小于 14,因此当随机值大于 12 时,它超出了数组的范围.

【讨论】:

  • 是的,C# 是 0-indexed。
猜你喜欢
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 2014-05-17
相关资源
最近更新 更多