System.FormatException异常求助:记事本计算器运行报错排查
问题:记事本计算器程序抛出System.FormatException异常
开发简单记事本计算器时,运行至第24行(Calculate方法中的int.Parse(stNum[0]))抛出System.FormatException,提示Input string was not in a correct format。尝试过TryParse但未成功,以下是原始代码及输入文件截图:
原始代码
private static string Reader(string path) { StreamReader sr = new StreamReader(path); string str = sr.ReadToEnd(); sr.Close(); return str; } private static int Calculate(string st) { string[] stNum = st.Split(','); int sum = int.Parse(stNum[0]); //code that causes problems for(int i=1; i<=stNum.Length-1; i++) { sum = +int.Parse(stNum[i]); } return sum; } private void Form1_Load(object sender, EventArgs e) { string[] data = Reader("input.txt").Split('\r'); MessageBox.Show("There are" + data[0] + "questions in total"); int[] ans = new int[int.Parse(data[0])]; for(int n=0; n<= int.Parse(data[0])-1; n++) { ans[n] = Calculate(data[n+1]); MessageBox.Show("The answer for the"+(n+1) +"question is" + ans[n]); } FileInfo fInfo = new FileInfo("output.txt"); StreamWriter sw =fInfo.CreateText(); foreach(int a in ans) { sw.WriteLine(a); sw.Flush(); sw.Close(); } }
输入记事本内容

问题排查与解决
1. 核心报错原因
- 换行符处理错误:Windows文本换行是
\r\n,用Split('\r')分割后,每行末尾会残留\n(比如data[0]实际是"2\n",data[1]是"1,2,3\n"),这些带换行符的字符串无法被int.Parse解析。 - 累加逻辑错误:
sum = +int.Parse(stNum[i]);是直接覆盖sum的值,而非累加,应该用sum += int.Parse(stNum[i]);。 - 流提前关闭:
StreamWriter的Close()放在foreach循环内,第一次循环就会关闭流,后续写入会失败。 - 无输入校验:未处理空字符串、空白字符等无效输入场景。
修正后的完整代码
private static string Reader(string path) { // 使用using自动释放资源,避免手动Close遗漏 using (StreamReader sr = new StreamReader(path)) { return sr.ReadToEnd(); } } private static int Calculate(string st) { string[] stNum = st.Split(','); int sum = 0; foreach (string numStr in stNum) { // 去除字符串前后空白(含换行符、空格) string trimmedStr = numStr.Trim(); if (int.TryParse(trimmedStr, out int num)) { sum += num; } else { throw new FormatException($"无效数字格式:{trimmedStr}"); } } return sum; } private void Form1_Load(object sender, EventArgs e) { string content = Reader("input.txt"); // 正确分割换行并移除空行 string[] data = content.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); // 校验第一行的题目数量格式 if (data.Length == 0 || !int.TryParse(data[0].Trim(), out int totalQuestions)) { MessageBox.Show("输入文件格式错误:第一行必须是有效数字"); return; } MessageBox.Show($"There are {totalQuestions} questions in total"); // 校验题目数量是否足够 if (data.Length < totalQuestions + 1) { MessageBox.Show("输入文件的题目数量不足"); return; } int[] ans = new int[totalQuestions]; for (int n = 0; n < totalQuestions; n++) { try { ans[n] = Calculate(data[n + 1]); MessageBox.Show($"The answer for the {n+1} question is {ans[n]}"); } catch (Exception ex) { MessageBox.Show($"第{n+1}题计算错误:{ex.Message}"); } } // 使用using自动管理写入流 using (StreamWriter sw = new StreamWriter("output.txt")) { foreach (int a in ans) { sw.WriteLine(a); } sw.Flush(); } }
额外优化说明
- 用
using语句管理流资源,自动释放,避免资源泄漏。 - 所有字符串转int前先调用
Trim(),清除空白字符干扰。 - 加入多层输入校验,提前拦截格式错误并给出明确提示。
内容的提问来源于stack exchange,提问作者inca2005
相关产品推荐
相关产品推荐

