尝试将 int 从文件加载到 2d 数组中,收到"Input string was not in a correct format"错误



我一直在尝试用C#完成游戏设计类的赋值,遇到的问题之一是我无法加载带有所有加载信息的Save1.game文本文件,我收到一个"System.FormatException:'输入字符串的格式不正确。'"错误。

目前,这个任务包括一个小面板,玩家可以在其中设计一个Sokoban(https://en.wikipedia.org/wiki/Sokoban)地图,我已经完成了这一部分,现在我必须将保存文件加载到我的程序中,然后将"瓷砖"(瓷砖只是物品所在的小方块(生成到实际玩游戏的不同面板中。

到目前为止,我已经尝试过一行一行地加载文件并将其写入字符串数组。我还尝试将整个文件写入字符串并使用.split(','(函数,但没有成功。我尝试过很多想法,但老实说,我已经忘记了每一个。


我在玩游戏的窗体上的加载按钮:

private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openLevelDialog = new OpenFileDialog();
openLevelDialog.Title = "Select level to load";

if (openLevelDialog.ShowDialog() == DialogResult.OK)
{
string MyString = System.IO.File.ReadAllText(openLevelDialog.FileName);

int i = 0;
int j = 0;
//My array where I will just dump the whole file into.
int[,] result = new int[10, 10];
//foreach loop where I attempt to go line-by-line and split the individual numbers by ','
foreach (var row in MyString.Split('n'))
{
j = 0;
foreach (var col in row.Trim().Split(','))
{
result[i, j] = int.Parse(col.Trim()); //Exception happens here.
j++;
}
i++;
}
//Just an attempt to display what the variable values in my form, ignore this part.
for (int a = 0; a < result.GetLength(0); a++)
{
for (int w = 0; w < result.GetLength(1); w++)
{
label1.Text += result[a,w].ToString();
}
}  
}
}

这是Game1.GAME文件

2,2<---这是地图的大小,2X2=4个瓦片。---

0,0,0<---这是tile[0,0],根据tile.cs类中的TileTypes枚举,它应该是空的,因此是第三个0。---

0,1,1<---这是tile[0,1],根据tile.cs类中的TileTypes枚举,它应该是"The Hero",因此是1--

1,0,2<---这是tile[1,0],根据tile.cs类中的TileTypes枚举,它应该是一堵墙,因此是2---

1,1,3<---这是tile[1,1],根据tile.cs类中的TileTypes枚举,它应该是一个框,因此,3。---

注意:有一个值为"Destination"的第四个枚举,但在这个特定的映射中,我没有添加任何枚举

它通常看起来如何

2,2
0,0,0
0,1,1
1,0,2
1,1,3

我希望它能加载字符串,将其分割成int数组,但无论我做什么,我似乎都无法通过异常。

谢谢你提前到时间。


这是我在记事本++中的文件

我的System.IO返回

根据您提供的信息,您在最后一行出错,因为换行符在最后一条记录的末尾。

处理此问题的一种方法是检查row在迭代中是否为NullEmptyWhitespace,如果条件为true,则检查循环中的continue

foreach (var row in MyString.Split('n')) 
{
//skip iteration if row is null, empty, or whitespace
if (string.IsNullOrWhitespace(row))
continue;

相关内容

最新更新