c# 索引超出数组的边界(转弯的概率)

本文关键字:转弯 概率 边界 数组 索引 | 更新日期: 2023-09-27 18:33:27

我正在尝试制作一个迷宫,然后由计算机通过随机选择路径来运行,但我不断出现索引超出范围的错误,我不确定为什么。我看过其他帖子,似乎与数组的设置方式有关,但我无法弄清楚这段代码出了什么问题。此行有错误:

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

其他信息:索引超出数组边界。

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

c# 索引超出数组的边界(转弯的概率)

您可以在下面添加检查以检查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(); }
}