运行C#代码触发System.FormatException异常的问题咨询
问题根源与修复方案
嘿,我一眼就瞅出问题所在了——当你输入空行时,代码仍然会尝试把空字符串转换成整数,这直接触发了System.FormatException。
咱们来拆解下你的代码逻辑:
bool emptyline = false; List<string> arry = new List<string>(); List<int> arryint = new List<int>(); for (int i = 0; emptyline == false; i++) { arry.Add(Console.ReadLine()); if (arry[i] == string.Empty) { emptyline = true; } arryint.Add(int.Parse(arry[i])); // 这里就是坑! }
当你输入空行时,arry[i]会被设为空字符串,你把emptyline标记为true,但循环并不会立刻终止——下面的int.Parse(arry[i])还是会执行。而int.Parse根本没法把空字符串解析成整数,自然就抛出异常了。
另外,你的代码还有个隐藏问题:如果用户输入的不是数字(比如字母、符号),同样会触发这个异常。所以咱们得一起把这两个问题都解决掉。
修复方案1:添加判断跳过空行解析
bool emptyline = false; List<string> arry = new List<string>(); List<int> arryint = new List<int>(); for (int i = 0; !emptyline; i++) { string input = Console.ReadLine(); arry.Add(input); // 先判断是否是空行,是的话标记终止并跳过解析 if (string.IsNullOrEmpty(input)) { emptyline = true; continue; } // 用TryParse替代Parse,优雅处理非数字输入 if (int.TryParse(input, out int num)) { arryint.Add(num); } else { Console.WriteLine("输入不是有效的整数,请重新输入!"); i--; // 回退索引,因为这次输入无效,不算入循环次数 } }
修复方案2:用while循环简化逻辑(更推荐)
直接把空行作为循环终止条件,逻辑更清晰,也避免了原代码的索引问题:
List<string> arry = new List<string>(); List<int> arryint = new List<int>(); string input; // 当输入不为空时继续循环 while ((input = Console.ReadLine()) != string.Empty) { arry.Add(input); // 尝试解析整数,失败则提示用户 if (int.TryParse(input, out int num)) { arryint.Add(num); } else { Console.WriteLine("无效的整数输入,请检查后重新输入!"); } }
这两种方案都能解决你当前的异常问题,同时还能处理非数字输入的情况,让代码更健壮。
内容的提问来源于stack exchange,提问作者GDD
相关产品推荐
相关产品推荐

