2015-12-23 24 views
0

我是一個初學C#開發人員,我找不到一些我得到的錯誤。讓我解釋我爲創建計算器所做的步驟。c#在桂創建一個計算器出錯

首先我創建2個變量

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

我這樣分配的每個值的所有按鈕。目前一切都很好。

下一步是計算公式的結果在textbox1.Text

我已經分配了textChangedtextBox1.Text(假定在最後這將是什麼被寫入輸入)

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

之後,當我例如在textBox1.Text中輸入(3 + 2)時,該值將等於輸入。

,當我運行它被鎖定,所以沒有任何腳本中的計算部分執行

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 
    } 

後。

+0

請閱讀[問]並創建[mcve]。 「錯誤」和「被鎖定」和「什麼都不做」對問題描述並不真正有幫助。準確解釋你輸入的內容,你期望看到什麼以及實際發生了什麼;還會顯示您嘗試解決問題的方式。 – CodeCaster

回答

1

不能將「3 + 2」轉換爲字符串。它不能簡單地在Convert.Int32上轉換爲5。它拋出一個異常

4

我不明白這是什麼代碼點:

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

如果改變文本框的文本,該方法textBox1_TextChanged將被調用一次,再而三。我不認爲這是必要的。

然後在你的Calculate_Click方法中,你這樣做可怕的錯誤。我想你誤解了Convert.ToInt32的使用。你認爲如果你這樣寫:

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

i會等於5吧? 不!Convert類的方法不識別數學表達式。他們只識別數字,如5,999,123和1234567.

那麼,如果它不能識別你的表情會發生什麼? A FormatException將被拋出。我認爲這就是爲什麼你說有一個「錯誤」。

如何解決這個問題?那麼,你當然需要找到一個「數學表達式解析器」!您可以在Google上輕鬆找到其中的一款。然後你只需在你的項目中引用這個庫,並使用它的一個方法和BAM!有用!

+1

大量使用「BAM」 – Glubus