【问题标题】:c# Index was outside the bounds of the array (Probability for making a turn)c#索引超出了数组的范围(转弯的概率)
【发布时间】:2016-02-05 02:36:50
【问题描述】:

我正在尝试制作一个迷宫,然后通过随机选择一条路径由计算机运行,但我不断收到 Index out of range 错误,我不知道为什么。我看过其他帖子,似乎它与数组的设置方式有关,但我无法弄清楚这段代码有什么问题。此行有错误:

抛出异常:mazeai.exe 中的“System.IndexOutOfRangeException”

附加信息:索引超出了数组的范围。

if (popularity[turnNumber] > 500)

我想知道如何解决这个错误,如果有人能告诉我是什么原因造成的? 其余代码如下

    static bool isDead = false;
    static int turnNumber = 0;
    static Random rand  = new Random();
    static int turnProb = rand.Next(1, 1001);
    static int turnDirection = 0;
    static int[] popularity = new int[10];
    static int[] turns = new int[10];
    static int[] maze = new int[10];

 public static void OpponetAI()
{
    if (popularity[turnNumber] > 500)
    {
        turnRight();
    }
    else { turnLeft(); }
}

【问题讨论】:

  • 显然turnNumber 在某些时候变得大于 9。但是,我们看不到 int 在哪里增加。
  • 查看您的 turnNumber 值。要发生该错误,在评估时它必须 > 9 或
  • 看起来更像是一个代码审查问题,而不是一个常见问题,除了提问者之外,解决这个问题对任何人都没有好处。
  • 回合数在回合成功时加上,总是在0-9的范围内。如果您需要,我可以发布其余的重要代码。
  • "回合数在回合成功时加上,始终在0-9的范围内。"坦率地说,如果你在那里遇到错误,它可能不在你的预期范围内......你不能在 IDE 抛出异常时检查它的值吗?假设您使用的是 VS?

标签: c# arrays


【解决方案1】:

您可以添加下面的检查来检查 turnNumber 的值。

public static void OpponetAI()
{
    if (popularity.Length <= turnNumber)
    {
        //add break point here, if you enter this break point,
        //then next "popularity[turnNumber]" will throw exception.
        //popularity only accept popularity[0] to popularity[popularity.Length-1]
    }

    if (popularity[turnNumber] > 500)
    {
        turnRight();
    }
    else { turnLeft(); }
}

【讨论】:

  • 看起来已经修复了。
猜你喜欢
  • 1970-01-01
  • 2015-11-06
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多