![](/img/trans.png)
[英]System.FormatException: Input string was not in a correct format
[英]System.FormatException:Input string was not in a correct format
问题:
我试图制作一个简单的记事本计算器,但它会在第 24 行停止并向我显示此错误。
我尝试了什么:
我尝试使用TryParse
,但它对我不起作用,但也许我在编码方面经验不足,无法正确使用它。
原始代码(没有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();
}
}
输入记事本:
使用十进制而不是整数:
private static decimal Calculate(string st)
{
string[] stNum = st.Split(',');
decimal sum = 0;
foreach (var num in stNum)
{
sum += decimal.Parse(num);
}
return sum;
}
有了链接,它看起来会更短更简单:
private static decimal Calculate(string st)
{
string[] stNum = st.Split(',');
return stNum.Sum(x => decimal.Parse(x));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.