Home > front end >  String To Double Error With Switch-Case Calculator
String To Double Error With Switch-Case Calculator

Time:07-10

Basically, the program calculates the two numbers we enter, according to the entered sign.

Program Picture

But I got an error:

Cannot implicitly convert type 'string' to 'double'

To be honest I don't have any idea about this. I'm still learning the language. Need help about this.

Code:

private void button1_Click(object sender, EventArgs e)
{
    int num1, num2;
    string sembol;
    double rslt;
    num1 = Convert.ToInt32(textBox1.Text);
    num2 = Convert.ToInt32(textBox2.Text);
    sembol = textBox3.Text;
    rslt = textBox4.ToString();
    
    switch (sembol)
    {
        case " ": rslt = num1   num2; break;
        case "-": rslt = num1 - num2; break;
        case "*": rslt = num1 * num2; break;
        case "/": rslt = num1 / num2; break;
    }
}

CodePudding user response:

This row is causing the trouble:

rslt = textBox4.ToString();

You're trying to read an string containing object information into a double, that won't work.

Just skip this line. Then add this:

textBox4.Text = rslt.ToString();

to your code after the switch-Statement.

private void button1_Click(object sender, EventArgs e)
{
    int num1, num2;
    string sembol;
    double rslt;
    //num1 = Convert.ToInt32(textBox1.Text);
    //num2 = Convert.ToInt32(textBox2.Text);
    // This will try to read the input and make sure that no exception is thrown due to non numeric input
    if(!int.TryParse(textBox1.Text, out num1) || !int.TryParse(textBox2.Text, out num2))
    {
       textBox4.Text = "INVALID INPUT";
       return;
    }
    sembol = textBox3.Text;
    
    switch (sembol)
    {
        case " ": rslt = num1   num2; break;
        case "-": rslt = num1 - num2; break;
        case "*": rslt = num1 * num2; break;
        case "/": rslt = num1 / num2; break;
        // This will handle anything that doesn't represent a valid operation
        default:
            textBox4.Text = "INVALID INPUT";
            return;
    }
    // Having checked every input for invalid characters, you can be sure rslt is properly set
    textBox4.Text = rslt.ToString();
}
  •  Tags:  
  • c#
  • Related