Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restructure this bit of code?

Tags:

c#

I'm designing a simple calculator using Visual C# but I'm running into an annoying runtime error (which is funny for a statically typed language).

First let me show you the partial code:

private float get_input()
{
    try
    {
        return float.Parse(textBox1.Text);
    }
    catch
    {
        textBox2.Clear();
        textBox2.AppendText("Invalid Input");
        return 0;
    }

}

private void button1_Click(object sender, EventArgs e)
{ 
    textBox2.Clear();
    float v = get_input();
    textBox2.AppendText((Math.Sin(v)).ToString());
}

The problem is that when I run the program, and let's say for example, I enter "a" into the input box, my program does handle the exception by displaying "Invalid input" into the output box. However, it then proceeds to calculate the sin or cos (etc) of the default float type. So the answer in the output box would look like: "invalid input1" or "invalid input0". I provided a screenshot:

I do realize this is because I'm telling it to append text right after I call the get_input() method, but I really don't know how to find a way around this. I've tried restructuring my code in like 7 ways but something always goes wrong.

like image 970
katie1245 Avatar asked Dec 09 '22 00:12

katie1245


1 Answers

Use TryParse instead of try...catch

private void button1_Click(object sender, EventArgs e)
{ 
    textBox2.Clear();
    float result;
    if (float.TryParse(textBox1.Text, out result))
    {
         textBox2.AppendText(Math.Sin(result).ToString());
    }
    else
    {
        textBox2.Text = "Invalid Input";
    }
}
like image 152
Kenneth Avatar answered Feb 02 '23 21:02

Kenneth