Making Decisions Using if...else


Making Decisions Using if...else

By far the most common decision-making construct used in programming is the if construct. A simple if construct looks like this:

if (expression)    ... statement to execute when expression is true;


The if construct uses Boolean logic, as discussed in Hour 12, "Performing Arithmetic, String Manipulation, and Date/Time Adjustments," to evaluate an expression to either true or false. The expression may be simple (if (x == 6)) or complicated (if (x==6 && y>10)). If the expression evaluates to true, the statement or block of statements (if enclosed in braces) gets executed. If the expression evaluates to false, Visual C# doesn't execute the statement or statement block for the if construct.

By the Way

Remember that compound statements, also frequently called block statements, can be used anywhere a statement is expected. A compound statement consists of zero or more statements enclosed in braces ({}). Following is an example of the if construct using a block statement:

if (expression)    {       statement 1 to execute when expression is true;       statement 2 to execute when expression is true;       ... statement n to execute when expression is true;    }



You're going to create a simple if construct in a Visual C# project. Create a new Windows Application named Decisions and follow these steps:

1.

Right click Form1.vs in the Solution Explorer, choose Rename, and change the name of the default form to frmDecisions.cs. Next, set the Text property of the form to Decisions Example.

2.

Add a new text box to the form by double-clicking the Textbox icon in the toolbox. Set the properties of the text box as follows:

Property

Value

Name

txtInput

Location

44,44


3.

Add a new button to the form by double-clicking the Button icon in the tool-box. Set the button's properties as follows:

Property

Value

Name

btnIsLessThanHundred

Location

156,42

Size

100,23

Text

Is text < 100?


Your form should now look like the one in Figure 13.1.

Figure 13.1. You'll use the if statement to determine whether the value of the text entered into the text box is less than 100.


You're now going to add code to the button's Click() event. This code will use a simple if construct and the int.Parse() method. The int.Parse() method is used to convert text into its numeric equivalent, and you'll use it to convert the text in txtInput into an integer. The if statement will then determine whether the number entered into the text box is less than 100. Double-click the button now to access its Click event, and enter the following code:

if (int.Parse(txtInput.Text)< 100)       MessageBox.Show("The text entered is less than 100.");


This code is simple when examined one statement at a time. Look closely at the first statement and recall that a simple if statement looks like this:

if (expression)    statement;


In the code you entered, expression is

int.Parse(txtInput.Text)< 100


What you are doing is asking Visual C# to evaluate whether the parsed integer is less than 100. In this case, Parse is a method of the int (integer) class. Int.Parse() converts a supplied string to an integer data typewhich can be used for numerical computations and evaluations. So, the value in the text box is cast to an integer and then compared to see if it is less than 100. If it is, the evaluation returns true. If the value is greater than or equal to 100, the expression returns false. If the evaluation returns true, execution proceeds with the line immediately following the if statement and a message is displayed. If the evaluation returns false, the line statement (or block of statements) following the if statement doesn't execute, and no message is displayed.

By the Way

If the user leaves the text box empty or enters anything other than an integer, an exception will be thrown. Therefore, you'd normally implement exception handling around this type of code or better yet add code that prevents the user from entering anything other than a number to begin with. You'll learn about exception handling in Hour 15, "Debugging Your Code."


Executing Code When Expression Is False

If you want to execute some code when expression evaluates to false, include the optional else keyword, like this:

if (expression)    statement to execute when expression is true; else    statement to execute when expression is false;


By the Way

If you want to execute code only when expression equates to false, not when TRue, use the not-equal operator (!=) in the expression. Refer to Hour 12 for more information on Boolean logic.


By including an else clause, you can have one or more statements execute when expression is TRue and other statements execute when the expression is false. In the example you've built, if a user enters a number less than 100, the user will get a message. However, if the number is greater than or equal to 100, the user receives no feedback. Modify your code to look like the following, which ensures that the user always gets a message:

if (int.Parse(txtInput.Text)< 100)    MessageBox.Show("The text entered is less than 100."); else    MessageBox.Show("The text entered is greater than or equal to 100.");


Now, if the user enters a whole number less than 100, the message The text entered is less than 100 is displayed, but nothing more. When Visual C# encounters the else statement, it ignores the statement(s) associated with the else statement. The statements for the else condition execute only when expression is false. Likewise, if the user enters text that is greater than or equal to 100, the message The text entered is greater than or equal to 100 is displayed, but nothing more; when expression evaluates to false, execution immediately jumps to the else statement.

Follow these steps:

1.

Click Save All on the toolbar to save your work.

2.

Press F5 to run the project.

3.

Enter a whole number into the text box and click the button.

A message box appears, telling you whether the number you entered is less than or greater than 100 (see Figure 13.2).

Figure 13.2. As implied with this message box, the if statement gives you great flexibility in making decisions.


Feel free to enter other whole numbers and click the button as often as you like. When you're satisfied that the code is working, choose Stop Debugging from the Debug menu.

Did you Know?

Get comfortable with if; chances are good that you'll include at least one in every project you create.


Nesting if...else Constructs

As mentioned earlier, you can nest if statements to further refine your decision making. The format you use can be something like the following:

if ( expression1 )    if ( expression2 )    ...    else       ... else    ...





Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net