C#FormatException未处理

时间:2014-12-31 14:29:44

标签: c#

我正在使用Microsoft Visual C#2010 Express。我目前正试图让我的计算器做加法和减法,但我一直收到这个错误?我在整个计算器中使用switch语句。

        private void Add_Click(object sender, EventArgs e)
    {
        //Storing the number on display in variables total1 for further use
        //Making addition happen before = is clicked
        total1 = total1 + double.Parse(textDisplay.Text);
        textDisplay.Text = textDisplay.Text + Add.Text;
        theOperator = "+";

    }

    private void Subtract_Click(object sender, EventArgs e)
    {
        total1 = total1 + double.Parse(textDisplay.Text);
        textDisplay.Clear();

        theOperator = "-";

    }

    private void Equals_Click(object sender, EventArgs e)
    {
      switch(theOperator)
      {
          case "+": //Addition
                    total1 = total1 + double.Parse(textDisplay.Text);---> error in this line
                    textDisplay.Text = result.ToString();
                    total1 = 0;
                    break;

          case "-": //Subtraction
                    result = total1 - double.Parse(textDisplay.Text);--->error in this line
                    textDisplay.Text = result.ToString();
                    total1 = 0;
                    break;

1 个答案:

答案 0 :(得分:4)

在问题专栏中,您有:

double.Parse(textDisplay.Text)

但是在你的Add_Click方法中,你有这个:

textDisplay.Text = textDisplay.Text + Add.Text;

我假设您的Add按钮标签是一个数字(可能是Add+)。因此,当您运行上面的行时,您会得到以下任何一种:

  • 1234Add
  • 1234 +

这会在您将其传递给double.Parse时导致异常,因为此函数不接受错误输入(因此除非textDisplay.Text是数字,否则会出错)。如果您想测试错误输入,则需要使用double.TryParse


以下是如何测试错误输入的示例:

private void Equals_Click(object sender, EventArgs e)
{
    // Remove the operator from the value we want to process.
    // It is expected this will be at the end.
    var userValue = textDisplay.Text;
    if (userValue.EndsWith(theOperator))
    {
        userValue = userValue.Substring(0, userValue.Length - theOperator.Length).Trim();
    }

    // Test for valid input.
    // Test our "userValue" variable which has the pending operator removed.
    double value;
    if (!double.TryParse(userValue, out value))
    {
        // Invalid input.
        // Alert the user and then exit this method.
        MessageBox.Show("A number was not entered.");
        return;
    }
    // If we get here, the "value" variable is a valid number.
    // Use it for calculations.

    ...

修改

作为旁注,您在OP中使用和重置resulttotal1的方式确实存在一些逻辑问题。我不打算为你做功课,但最好回顾一下你对这些变量的用法。