简体   繁体   中英

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.

I am getting a:

IndexOutOfRange exception

..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.

I have _gameWidth and _gameHeight created as follows, outside of main but still inside the class:

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.

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. 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. Just type "for<tab><tab>" .

Your program might benefit from the Code Review Stack Exchange site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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