|
-
October 6th, 2010, 10:38 AM
#1
What's wrong with this code?
It won't compile because of a "Use of unassigned local variable 'answer' "
Any help would be appreciated, and don't flame because I'm still a beginner.
Code:
string theOperator;
private void btnAnswer_Click(object sender, EventArgs e)
{
int firstTextBoxNumber = int.Parse(tbFirstNumber.Text);
int secondTextBoxNumber = int.Parse(tbSecondNumber.Text);
int answer;
theOperator = tbOperatorSymbol.Text;
switch (theOperator)
{
case "+":
answer = firstTextBoxNumber + secondTextBoxNumber;
break;
case "-":
answer = firstTextBoxNumber - secondTextBoxNumber;
break;
case "*":
answer = firstTextBoxNumber * secondTextBoxNumber;
break;
case "/":
answer = firstTextBoxNumber / secondTextBoxNumber;
break;
default:
//Insert Code
break;
}
MessageBox.Show(answer.ToString());
}
-
October 6th, 2010, 11:05 AM
#2
Re: What's wrong with this code?
If the "switch" statement goes through "default" the "answer" variable does not get assigned, i.e. MessageBox at the end of the program does not know what to use if your program "switch" goes in "default".
To fix is you can either assign "answer" when declaring it, i.e.
Code:
int answer = 0; // or something else
or directly in the "switch" statement after "default":
Code:
...
default:
answer = 0; // or whatever you wish
break;
-
October 6th, 2010, 04:36 PM
#3
Re: What's wrong with this code?
Thanks man, but I already figured that out after I posted...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|