【发布时间】:2014-06-10 09:39:31
【问题描述】:
我无法对此问题应用任何解决方案。此行发生异常: currentMap[row, col] = Int32.Parse(s);我想要做的是将这个方法传递给一个特定的文件来存储这样的数字行:
1,1,1
1,0,1
1,1,1
然后我希望将每个数字存储在返回的 int[,] currentMap 中。我使用的文件不包含大数字。我认为我正在创建的数组的大小是正确的,所以我不明白为什么这不起作用。我习惯于在 java 中使用 NextInt 做类似的事情,但我找不到 c# 的任何替代品。
感谢您的帮助。
private int[,] LoadMapArray(String filename)
{
int[,] currentMap;
int rows = 0;
int cols = 0;
StreamReader sizeReader = new StreamReader(filename);
using (var reader = File.OpenText(filename))
{
while (reader.ReadLine() != null)
{
string line = sizeReader.ReadLine();
cols = line.Length;
rows++;
}
}
currentMap = new int[rows,cols];
StreamReader sr = new StreamReader(filename);
for (int row = 0; row < rows + 1; row++)
{
string line = sr.ReadLine();
string[] split = new string[] {","};
string[] result;
result = line.Split(split, StringSplitOptions.None);
int col = 0;
foreach (string s in result)
{
currentMap[row, col] = Int32.Parse(s);
col++;
}
}
return currentMap;
}
编辑:更改我访问文件的方式后,代码已修复。然后我不得不更改它以捕获 null:
for (int row = 0; row < rows + 1; row++)
{
string line = sr.ReadLine();
string[] split = new string[] { "," };
string[] result;
if (line != null)
{
result = line.Split(split, StringSplitOptions.None);
int col = 0;
foreach (string s in result)
{
currentMap[row, col] = Int32.Parse(s);
col++;
}
}
}
【问题讨论】:
-
你有没有试过调试它,看看它坏的时候s的值是多少?
-
能否提供异常详情?
-
磁盘上的文件有多大?
-
将
for (int row = 0; row < rows + 1; row++)更改为for (int row = 0; row < rows; row++)。现有代码导致 index 超出范围异常,而不是 integer 超出范围。 -
@KrisVandermotten 没有注意到这一点。很好的收获。
标签: c# parsing int streamreader