An easier way to code the calculator is by using a switch
statement instead of an else if statement. A switch statement allows
you to check which of more than one option is true. It's like a list of if statements.
The structure of a switch statement looks like this:
We'll use our calculator as a coding example.
Our four buttons set a Boolean variable to either true or false. Instead of doing this, we could have the buttons put a symbol into a string variable. Like this:
string theOperator;
private void btnPlus_Click(object sender, EventArgs e)
{
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
txtDisplay.Clear();
theOperator = "+";
}
So the last line of code puts the + symbol into a string variable we've
called theOperator. It will only do this if the button is clicked. The
other buttons can do the same. We can then use a switch statement in our Equals
button to check what is in the variable we've called theOperator. This
will tell us which button was clicked. Here's the code that would go in the
Equals button.
case "+" :
The code to add up goes on a new line. After the code, the break word is used.
So what you're saying is:
"If it's the case that theOperator holds a + symbol,
then execute some code"
We have three more case parts to the switch statement, one for each of the
math symbols. Notice the addition of this, though:
default :
//DEFAULT CODE HERE
break;
You use default instead case just "in case" none of
the options you've thought of are what is inside of your variable. You do this
so that your programme won't crash!break;
Exercise E
Adapt the equals button on your calculator so that it uses a switch statement instead of if .. else if Statements. You can get rid of all your Boolean variables.
Switch statements can be quite tricky to get the hang of. But they are very useful if you want to test a variable for a list of possible things that could be in the variable.
0 comments:
Post a Comment