开发者

NullReferenceException when reading from a file

I need to read a file structured like this:

01000
00030
00500
03000
00020

And put it in an array like this:

int[,] iMap = new int[iMapHeight, iMapWidth] {
{0, 1, 0, 0, 0},
{0, 0, 0, 3, 0},
{0, 0, 5, 0, 0},
{0, 3, 0, 0, 0},
{0, 0, 0, 2, 0},
};

Hopefully you see what I'm trying to do here. I was confused how to do this so I asked here on SO, but the code I got from it gets this error:

Object reference not set to an instance of an object.

I'm pretty new to this so I have no idea how to fix it... I only barely know the code:

protected void ReadMap(string mapPath)
{
    using (var reader = new StreamReader(mapPath))
    {
        for (int i = 0; i < iMapHeight; 开发者_如何学Goi++)
        {
            string line = reader.ReadLine();
            for (int j = 0; j < iMapWidth; j++)
            {
                iMap[i, j] = (int)(line[j] - '0');
            }
        }
    }
}

The line I get the error on is this:

iMap[i, j] = (int)(line[j] - '0');

Can anyone provide a solution?


On this line, StreamReader.ReadLine can return null if the end of file is reached:

string line = reader.ReadLine();

You should check for this condition and handle it appropriately.

string line = reader.ReadLine();
if (line == null)
{
    // Handle the error.
}

Also make sure that your input has at least iMapHeight * iMapWidth lines.

You should also make sure that your array is initialized. For example, add this line to the start of your method:

iMap = new int[iMapHeight, iMapWidth];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜