1

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; i++)
        {
            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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Joshua
  • 71
  • 6
  • Where are you creating the iMap object? In the constructor? – Andy White May 08 '10 at 23:35
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – ekad Jan 07 '19 at 12:38

1 Answers1

2

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];
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452