Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String To Double Error With Switch-Case Calculator

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

Program Picture

But I got an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading