从文件读取时出现 NullReferenceException
我需要读取一个如下结构的文件:
01000
00030
00500
03000
00020
并将其放入这样的数组中:
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},
};
希望您看到我在这里尝试做的事情。我很困惑如何做到这一点,所以我在这里询问,但我从中得到的代码收到此错误:
对象引用未设置为 对象的实例。
我对此很陌生,所以我不知道如何解决它...我几乎不知道代码:
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');
}
}
}
}
我收到错误的行是这样的:
iMap[i, j] = (int)(line[j] - '0');
任何人都可以提供解决方案吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在此行中,
StreamReader.ReadLine
可能返回 null:
您应该检查这种情况并适当处理。
另请确保您的输入至少包含
iMapHeight * iMapWidth
行。您还应该确保您的数组已初始化。例如,将此行添加到方法的开头:
On this line,
StreamReader.ReadLine
can return null if the end of file is reached:You should check for this condition and handle it appropriately.
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: