【发布时间】: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#