繁体   English   中英

尝试将 int 从文件加载到二维数组中,收到“输入字符串格式不正确”错误

[英]Attempting to load int from file into 2d array, receiving “Input string was not in a correct format” error

我一直在尝试在 C# 中完成我的游戏设计 class 的作业,我遇到的问题之一是我无法加载包含所有加载信息的 Save1.GAME 文本文件,我收到“System.FormatException: '输入字符串的格式不正确。'”错误。

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

到目前为止,我已经尝试加载文件并将其逐行写入字符串数组。 我还尝试将整个文件写入字符串并使用 the.split(',') function,但无济于事。 我已经尝试了很多想法,老实说我已经忘记了其中的每一个。


我在将要玩游戏的表单上的加载按钮:

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 <--- 这是 map 的大小,2X2 = 总共 4 个图块。 ---

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

0,1,1 <--- 这是 tile [0,1] 并且根据我的 tile.cs class 中的 TileTypes 枚举,它应该是“英雄”,因此是 1。---

1,0,2 <--- 这是瓷砖 [1,0] 并且根据我的 tile.cs class 中的 TileTypes 枚举,它应该是一堵墙,因此 2。---

1,1,3 <--- 这是 tile [1,1] 并且根据我的 tile.cs class 中的 TileTypes 枚举,它应该是一个盒子,因此是 3。---

注意:有一个值为“Destination”的第四个枚举,但在这个特定的 map 中,我只是没有添加任何内容。

它通常看起来如何

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

我希望它只会加载字符串,将其切碎到 int 数组中,但无论我做什么,我似乎都无法克服异常。

谢谢你的时间提前。


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

我的 System.IO 返回

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

处理此问题的一种方法是检查迭代中的row是否为NullEmptyWhitespace ,如果该条件为truecontinue循环。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM