简体   繁体   English

C#IndexOutOfRange数组异常

[英]C# IndexOutOfRange Array Exception

I'm trying to create a 2D char array to hold a grid of chars which will be used as a sort of 'map' for a 2D console game. 我正在尝试创建一个2D字符数组来保存字符网格,这些字符将用作2D控制台游戏的一种“地图”。

I am getting a: 我得到一个:

IndexOutOfRange exception IndexOutOfRange异常

..and cannot see why. ..并不明白为什么。 I've stepped through the code in debug mode and still cannot see the issue. 我已经在调试模式中完成了代码,仍然无法看到问题。

It steps through the code fine until it hits X = 25 and Y = 1 , the upper right boundary of my grid. 它逐步完成代码,直到它达到X = 25Y = 1 ,即网格的右上边界。

I have _gameWidth and _gameHeight created as follows, outside of main but still inside the class: 我有_gameWidth_gameHeight创建如下,在main之外但仍然在类中:

static int _gameWidth = 25;
static int _gameHeight = 15;

Following is the code that fails, when trying to generate and populate the grid. 以下是在尝试生成和填充网格时失败的代码。 It fails at this point: 它在这一点上失败了:

else if (x == _gameWidth && y == 1)
    _grid[x, y] = '╕';



static void GenerateGrid()
{
    for (int y = 1; y <= _gameHeight; y++)
    {
        for (int x = 1; x <= _gameWidth; x++)
        {
            if (x == 1 && y == 1)
                _grid[x, y] = '╒';
            else if (x == _gameWidth && y == _gameHeight)
                _grid[x, y] = '╛';
            else if (x == _gameWidth && y == 1)
                _grid[x, y] = '╕';
            else if (x == 1 && y == _gameHeight)
                _grid[x, y] = '╘';
            else if ((x != 1 && y == _gameHeight) || (x != _gameWidth && y == 1))
                _grid[x, y] = '═';
            else if ((x == 1 && y > 1 && y < _gameHeight) || (x == _gameWidth && y > 1 && y < _gameHeight))
                _grid[x, y] = '│';
            else
                _grid[x, y] = 'x';

        }
        Console.WriteLine("");
    }
}

Change 更改

for (int i = 1; i <= gameHeight; i++)

to

for (int i = 0; i < gameHeight; i++)

and do the same for width. 并为宽度做同样的事情。

EDIT: This is because array indexes start at the number 0 and end with the length of the array minus 1. 编辑:这是因为数组索引从数字0开始,结束时数组的长度减去1。

This exception means that you have accessed an invalid index. 此异常表示您已访问无效索引。 From the way you have written the loop I can tell that you think that indexes go from 1 to the length of the array. 从你编写循环的方式我可以看出你认为索引从1到数组的长度。 Arrays are zero-based, though. 但是,数组是从零开始的。 Use the standard loop form: 使用标准循环形式:

for (int i = 0; i < length; i++)

Your loop starts at one. 你的循环从一开始。 You can use the Visual Studio for loop template. 您可以使用Visual Studio for循环模板。 Just type "for<tab><tab>" . 只需输入"for<tab><tab>"

Your program might benefit from the Code Review Stack Exchange site. 您的程序可能会受益于Code Review Stack Exchange站点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM