Home > Mobile >  System.FormatException:Input string was not in a correct format
System.FormatException:Input string was not in a correct format

Time:12-27

Problem:

I was trying to make a simple notepad calculator, but it will stop at the 24th line and show me this error.

What I tried:

I tried to use the TryParse but it didn't work for me, but maybe I'm just too inexperienced in coding to use it properly.

The original code(without 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();
    }
}

The input notepad:

image

CodePudding user response:

use decimal instead of int:

private static decimal Calculate(string st)
{
    string[] stNum = st.Split(',');
    decimal sum = 0;
    foreach (var num in stNum)
    {
        sum  = decimal.Parse(num);
    }
    return sum;
}

with link it would look shorter and simpler:

private static decimal Calculate(string st)
{
    string[] stNum = st.Split(',');
    return stNum.Sum(x => decimal.Parse(x));
}
  • Related