簡體   English   中英

System.FormatException:輸入字符串的格式不正確

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM