类型' System.FormatException'的未处理异常使用Parse时出现mscorlib.dll错误

时间:2015-02-14 17:32:12

标签: c# parsing

编程世界的新手,必须完成此处列出的作业:Reading and processing input

现在,我终于围绕如何编写代码(如下所示),但我继续得到“mscorlib.dll中发生了'System.FormatException'类型未处理的异常。附加信息:输入字符串格式不正确。“当我尝试运行我的程序时。它继续标记为“gross = double.Parse(inputvaluetwo);”,这可能是因为那里没有输入。有人可以帮忙吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SalesProgram
{
    class SalesProgram
    {
        static void Main(string[] args)
        {
            double sales;
            double gross;
            double retirement;
            double social;
            double tax;
            string inputvalue;
            string inputvaluetwo;
            string inputvaluethree;
            string inputvaluefour;
            string inputvaluefive;
            string name;
            Console.Write("Enter your name: ");
            name = Console.ReadLine();
            Console.WriteLine("How much did you sell in dollars? ");
            inputvalue = Console.ReadLine();
            sales = double.Parse(inputvalue);
            Console.ReadKey();
            Console.WriteLine("Your gross pay is");
            Console.ReadKey();
            Console.WriteLine(sales * 0.07);
            inputvaluetwo = Console.ReadLine();
            gross = double.Parse(inputvaluetwo);
            Console.ReadKey();
            Console.WriteLine("Your retirement deduction is:");
            Console.WriteLine(gross * 0.15);
            inputvaluethree = Console.ReadLine();
            retirement = double.Parse(inputvaluethree);
            Console.ReadKey();
            Console.WriteLine("Your tax deduction is:");
            Console.WriteLine(gross * 0.18);
            inputvaluefour = Console.ReadLine();
            tax = double.Parse(inputvaluefour);
            Console.ReadKey();
            Console.WriteLine("Your social security deduction is:");
            Console.WriteLine(gross * 0.09);
            inputvaluefive = Console.ReadLine();
            social = double.Parse(inputvaluefive);
            Console.ReadKey();
            Console.WriteLine("Finally, your take-home, or net pay, is:");
            Console.WriteLine(gross-retirement-tax-social);
            Console.ReadKey();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这意味着某处的字符串值不正确。请改用:

double retirement ;
if(double.TryParse(inputvaluethree, out retirement) == false)
{
    Console.Write("Error on inputvaluethree : " + inputvaluethree);
}

答案 1 :(得分:0)

这意味着您输入的字符串无法转换为double。

使用以下代码段

if (Double.TryParse(string, out inputvalue))
{
  //do any additional stuff you want to with this inputvalue
}
else
{
  //do what you want to do if conversion fails
}

此重载与Double.Parse(String)方法的不同之处在于返回一个布尔值,该值指示解析操作是否成功而不是返回已解析的数值。它消除了在字符串无效且无法成功解析的情况下使用异常处理来测试FormatException的需要。

有关详情,请访问以下链接

https://msdn.microsoft.com/en-us/library/994c0zb1%28v=vs.110%29.aspx