简体   繁体   中英

c# creating a calculator in Gui getting errors

I am a beginner C# developer and I can't figure out some errors I get. Let me explain the steps I've done to create a calculator.

First I created 2 variables

string operand = string.Empty;
string input = string.Empty;
// input will be a number in string such as "1" or "2"
// operand will be an operand such as "-" or "+"

// I've created a button
 private void btn1_Click(object sender, EventArgs e)
    {
     // this is button number 1 so:
     input += "1"
     // and there is my textbox which shows what I entered.
     textbox1.Text += input;
     // it adds what is in input to the string in textbox1.
    }

I assigned every value like this for all the buttons. Everything is fine so far.

The next step is calculating the outcome of the formula in textbox1.Text

I've assigned the textChanged value to textBox1.Text (assuming in the end it will be what is written in the input)

 private void textBox1_TextChanged(object sender, EventArgs e)
    {
     // I added it's value to
     TextBox1.Text += input;
    }

After that, when I for example type (3 + 2) in textBox1.Text the value will be equal to input.

After that the calculating part is executed

 private void Calculate_Click(object sender, EventArgs e)
    {
        int a = Convert.ToInt32(textBox1.Text);
        string a1 = Convert.ToString(a);
        MessageBox.Show(a1);
        // so it converts the string "3 + 2" to int a = 3 + 2 and shows
    }

When I run the script it gets locked and does nothing.

I don't understand what is the point of this code:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    // i assigned it's value to
    TextBox1.Text += input;
}

If you change the text of the text box, the method textBox1_TextChanged will get called again and again and again. I don't think that's needed.

Then in your Calculate_Click method, you are doing it horribly wrong . I think you misunderstood the use of Convert.ToInt32 . You think that if you write this:

int i = Convert.ToInt32 ("3 + 2");

i will be equal to 5, right? No! Convert class's methods don't recognise math expressions. They only recognises numbers such as 5, 999, 123, and 1234567.

So what will happen if it cannot recognise your expressions? A FormatException will be thrown. And I think that's why you say there is an "error".

How to solve this problem? Well, you need to find a "Mathematical Expression Parser" of course! You can find one of those very easily on Google. And then you just reference the library in your project and use one of its methods and BAM! It works!

You cannot convert "3+2" to string. It cannot simply get converted to 5 on Convert.Int32 . It throws an exception

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM