I agree that you have to initialize the variable answer but there is another fix!
You have to use comboBox1.SelectedItem.ToString() instead of comboBox1.SelectedText.ToString()
;) Bye
Frage
private void answer_Click(object sender, EventArgs e)
{
int textbox1;
int textbox2;
int answer;
textbox1 = int.Parse(textBox1.Text);
textbox2 = int.Parse(textBox2.Text);
if (comboBox1.SelectedText.ToString() == "+")
{
answer = (textbox1 + textbox2);
}
else if (comboBox1.SelectedText.ToString() == "-")
{
answer = (textbox1 - textbox2);
}
else if (comboBox1.SelectedText.ToString() == "*")
{
answer = (textbox1 * textbox2);
}
else if (comboBox1.SelectedText.ToString() == "/")
{
answer = (textbox1 / textbox2);
}
// the error is here that says Use of unassigned local variable 'answer'
MessageBox.Show(answer.ToString());
}
the user input 12 on textbox1 and 2 on textbox2, so they choose '-' as their operations and then the messagebox should just display 10.
Lösung 2
I agree that you have to initialize the variable answer but there is another fix!
You have to use comboBox1.SelectedItem.ToString() instead of comboBox1.SelectedText.ToString()
;) Bye
Andere Tipps
Just assign your variable to a value when you defining it:
int answer = 0;
If any of your conditions doesn't match then answer
still will be unassigned.Compiler see this and warning you.
And your another mistake is, you are parsing textBox1.Text
and textBox2.Text
to integer, but you are not using that variables in your calculations.Change textboxone
to textbox1
and textboxtwo
to textbox2
Quick reformat for you:
private void answer_Click(object sender, EventArgs e)
{
int
textbox1 = int.Parse(textBox1.Text),
textbox2 = int.Parse(textBox2.Text),
answer = 0;
if (comboBox1.Text == "+")
answer = (textbox1 + textbox2);
else if (comboBox1.Text == "-")
answer = (textbox1 - textbox2);
else if (comboBox1.Text == "*")
answer = (textbox1 * textbox2);
else if (comboBox1.Text == "/")
answer = (textbox1 / textbox2);
MessageBox.Show(answer.ToString());
}
Hope you can see what was wrong with the original one.
Couple of observations: