If Then Decision Structures


If…Then Decision Structures

When a conditional expression is used in a special block of statements called a decision structure, it controls whether other statements in your program are executed and in what order they're executed. You can use an If…Then decision structure to evaluate a condition in the program and take a course of action based on the result. In its simplest form, an If…Then decision structure is written on a single line:

If condition Then statement

where condition is a conditional expression, and statement is a valid Visual Basic program statement. For example,

If Score >= 20 Then Label1.Text = "You win!"

is an If…Then decision structure that uses the conditional expression

Score >= 20

to determine whether the program should set the Text property of the Label1 object to “You win!” If the Score variable contains a value that's greater than or equal to 20, Visual Basic sets the Text property; otherwise, it skips the assignment statement and executes the next line in the event procedure. This sort of comparison always results in a True or False value. A conditional expression never results in maybe.

Testing Several Conditions in an If…Then Decision Structure

Visual Basic also supports an If…Then decision structure that you can use to include several conditional expressions. This block of statements can be several lines long and contains the important keywords ElseIf, Else, and End If.

If condition1Then      statements executed if condition1 is True ElseIf condition2Then      statements executed if condition2 is True [Additional ElseIf conditions and statements can be placed here]  Else      statements executed if none of the conditions is True End If

In this structure, condition1 is evaluated first. If this conditional expression is True, the block of statements below it is executed, one statement at a time. (You can include one or more program statements.) If the first condition isn't True, the second conditional expression (condition2) is evaluated. If the second condition is True, the second block of statements is executed. (You can add additional ElseIf conditions and statements if you have more conditions to evaluate.) If none of the conditional expressions is True, the statements below the Else keyword are executed. Finally, the whole structure is closed by the End If keywords.

The following code shows how a multiple-line If…Then structure could be used to determine the amount of tax due in a hypothetical progressive tax return. (The income and percentage numbers are from the projected United States Internal Revenue Service 2005 Tax Rate Schedule for single filing status.)

Dim AdjustedIncome, TaxDue As Double AdjustedIncome = 50000 If AdjustedIncome <= 7300 Then          '10% tax bracket     TaxDue = AdjustedIncome * 0.1 ElseIf AdjustedIncome <= 29700 Then     '15% tax bracket     TaxDue = 730 + ((AdjustedIncome - 7300) * 0.15) ElseIf AdjustedIncome <= 71950 Then     '25% tax bracket     TaxDue = 4090 + ((AdjustedIncome - 29700) * 0.25) ElseIf AdjustedIncome <= 150150 Then    '28% tax bracket     TaxDue = 14652.5 + ((AdjustedIncome - 71950) * 0.28) ElseIf AdjustedIncome <= 326450 Then    '33% tax bracket     TaxDue = 36548.5 + ((AdjustedIncome - 150150) * 0.33) Else                                    '35% tax bracket     TaxDue = 94727.5 + ((AdjustedIncome - 326450) * 0.35) End If

IMPORTANT
The order of the conditional expressions in your If…Then and ElseIf statements is critical. What happens if you reverse the order of the conditional expressions in the tax computation example and list the rates in the structure from highest to lowest? Taxpayers in the 10 percent, 15 percent, 25 percent, 28 percent, and 33 percent tax brackets are all placed in the 35 percent tax bracket because they all have an income that's less than or equal to 326,450. (Visual Basic stops at the first conditional expression that is True, even if others are also True.) Because all the conditional expressions in this example test the same variable, they need to be listed in ascending order to get the taxpayers to fall out in the right places. Moral: when you use more than one conditional expression, consider the order carefully.

This useful decision structure tests the double-precision variable AdjustedIncome at the first in-come level and subsequent income levels until one of the conditional expressions evaluates to True, and then determines the taxpayer's income tax accordingly. With some simple modifications, it could be used to compute the tax owed by any taxpayer in a progressive tax system, such as the one in the United States. Provided that the tax rates are complete and up to date and that the value in the AdjustedIncome variable is correct, the program as written will give the correct tax owed for single U.S. taxpayers for 2005. If the tax rates change, it's a simple matter to update the conditional expressions. With an additional decision structure to determine taxpayers' filing status, the program readily extends itself to include all U.S. taxpayers.

TIP
Expressions that can be evaluated as True or False are also known as Boolean expressions, and the True or False result can be assigned to a Boolean variable or property. You can assign Boolean values to certain object properties or Boolean variables that have been created by using the Dim statement and the As Boolean keywords.

In the next exercise, you'll use an If…Then decision structure that recognizes users as they enter a program—a simple way to get started with writing your own decision structures. You'll also learn how to use the MaskedTextBox control to receive input from the user in a specific format.

Validating users by using If…Then

  1. Start Visual Studio, and create a new project named My User Validation.

    The new project is created, and a blank form appears in the Designer.

  2. Click the form, and set the form's Text property to “User Validation”.

  3. Use the Label control to create a label on your form, and use the Properties window to set the Text property to “Enter your Social Security Number”.

  4. Use the Button control to create a button on your form, and set the button's Text property to “Sign In”.

  5. Click the MaskedTextBox control on the Common Controls tab in the Toolbox, and then create a masked text box object on your form below the label.

    The MaskedTextBox control is similar to the TextBox control that you have been using, but by using MaskedTextBox, you can control the format of the information entered by the user into your program. You control the format by setting the Mask property; you can use a predefined format supplied by the control or choose your own format. You'll use the MaskedTextBox control in this program to require that users enter a Social Security Number in the standard nine-digit format used by the United States Internal Revenue Service.

  6. With the MaskedTextBox1 object selected, click the Mask property in the Properties window, and then click the ellipses button next to it.

    The Input Mask dialog box appears, showing a list of your predefined formatting patterns, or masks.

  7. Click Social Security Number in the list.

    The Input Mask dialog box looks like this:

    graphic

    Although you won't use it now, take a moment to note the Custom option, which you can use later to create your own input masks using numbers and placeholder characters such as a hyphen (-).

  8. Click OK to accept Social Security Number as your input mask.

    Visual Studio displays your input mask in the MaskedTextBox1 object, as shown in the following illustration:

    graphic

  9. Double-click the Sign In button.

    The Button1_Click event procedure appears in the Code Editor.

  10. Type the following program statements in the event procedure:

    If MaskedTextBox1.Text = "555-55-1212" Then     MsgBox("Welcome to the system!") Else     MsgBox("I don't recognize this number") End If

    This simple If…Then decision structure checks the value of the MaskedTextBox1 object's Text property, and if it equals “555-55-1212”, the structure displays the message “Welcome to the system”. If the number entered by the user is some other value, the structure displays the message “I don't recognize you”. The beauty in this program, however, is how the MaskedTextBox1 object automatically filters input to ensure that it is in the correct format.

  11. Click the Save All button on the Standard toolbar to save your changes. Specify the c:\vb05sbs\chap06 folder as the location for your project.

  12. Click the Start Debugging button on the Standard toolbar.

    The program runs in the IDE. The form prompts the user to enter a Social Security number (SSN) in the appropriate format, and displays underlines and hypens to offer the user a hint of the format required.

  13. Type abcd to test the input mask.

    Visual Basic prevents the letters from being displayed, because letters do not fit the requested format. A nine-digit SSN is required.

  14. Type 1234567890 to test the input mask.

    Visual Basic displays the number 123-45-6789 in the masked text box, ignoring the tenth digit that you typed. Again, Visual Basic has forced the user's input into the proper format. Your form looks like this:

    graphic

  15. Click the Sign In button.

    Visual Basic displays the message “I don't recognize the number”, because the SSN does not match the number the If…Then decision structure is looking for.

  16. Click OK, delete the SSN from the masked text box, enter 555-55-1212 as the number, and then click Sign In again.

    This time the decision structure recognizes the number and displays a welcome message. You see the following message box:

    graphic

    Your code has prevented an unauthorized user from using the program, and you've learned a useful skill related to controlling input from the user.

  17. Exit the program.

Using Logical Operators in Conditional Expressions

You can test more than one conditional expression in If…Then and ElseIf clauses if you want to include more than one selection criterion in your decision structure. The extra conditions are linked together by using one or more of the logical operators listed in the following table.

Logical operator

Meaning

And

If both conditional expressions are True, then the result is True.

Or

If either conditional expression is True, then the result is True.

Not

If the conditional expression is False, then the result is True. If the conditional expression is True, then the result is False.

Xor

If one and only one of the conditional expressions is True, then the result is True. If both are True or both are False, then the result is False. (Xor stands for exclusive Or.)

TIP
When your program evaluates a complex expression that mixes different operator types, it evaluates mathematical operators first, comparison operators second, and logical operators third.

The following table lists some examples of the logical operators at work. In the expressions, it is assumed that the Vehicle string variable contains the value “Bike”, and the integer variable Price contains the value 200.

Logical expression

Result

Vehicle = "Bike" And Price < 300

True (both conditions are True)

Vehicle = "Car" Or Price < 500

True (one condition is True)

Not Price < 100

True (condition is False)

Vehicle = "Bike" Xor Price < 300

False (both conditions are True)

In the following exercise, you'll modify the My User Validation program to prompt the user for a personal identification number (PIN) during the validation process. To do this, you will add a second text box to get the PIN from the user, and then modify the If…Then clause in the decision structure so that it uses the And operator to verify the PIN.

Add password protection by using the And operator

  1. Display the User Validation form, and use the Label control to add a second descriptive label to the form below the first masked text box.

  2. Set the new label's Text property to “PIN”.

  3. Add a second MaskedTextBox control to the form below the first masked text box and the new label.

  4. Click the shortcut arrow in the MaskedTextBox2 object, and then click the Set Mask command to display the Input Mask dialog box.

  5. Click the Numeric (5 digits) input mask, and then click OK.

    Like many PINs found online, this PIN will be five digits long. Again, if the user types a password of a different length or format, it will be rejected.

  6. Double-click the Sign In button to display the Button1_Click event procedure in the Code Editor.

  7. Modify the event procedure so that it contains the following code:

    If MaskedTextBox1.Text = "555-55-1212" _ And MaskedTextBox2.Text = "54321" Then     MsgBox("Welcome to the system!") Else     MsgBox("I don't recognize this number") End If

    The statement now includes the And logical operator, which requires that the user's PIN correspond with his or her SSN before the user is admitted to the system. (In this case, the valid PIN is 54321; in a real-world program, this value would be extracted along with the SSN from a secure database.) I modified the earlier program by adding a line continuation character (_) to the end of the first line, and by adding the second line beginning with And.

  8. Click the Start Debugging button on the Standard toolbar.

    The program runs in the IDE.

  9. Type 555-55-1212 in the Social Security Number masked text box.

  10. Type 54321 in the PIN masked text box.

  11. Click the Sign In button.

    The user is welcomed to the program, as shown in the screen below.

    graphic

  12. Click OK to close the message box.

  13. Experiment with other values for the SSN and PIN.

    Test the program carefully to be sure that the welcome message is not displayed when other PINs or SSNs are entered.

  14. Click the Close button on the form when you're finished.

    The program ends, and the development environment returns.

    TIP
    You can further customize this program by using the PasswordChar property in the masked text box objects, which displays a placeholder character such as an asterisk (*) when the user types. (You specify the character by using the Properties window.) Using a password character gives users additional secrecy as they enter their protected password—a standard feature of such operations.

Short-Circuiting by Using AndAlso and OrElse

Visual Basic offers two logical operators that you can use in your conditional statements, AndAlso and OrElse. These operators work the same as And and Or respectively, but offer an important subtlety in the way they're evaluated that will be new to programmers experienced with Visual Basic 6.

Consider an If statement that has two conditions that are connected by an AndAlso operator. For the statements of the If structure to be executed, both conditions must evaluate to True. If the first condition evaluates to False, Visual Basic skips to the next line or the Else statement immediately, without testing the second condition. This partial, or short-circuiting, evaluation of an If statement makes logical sense—why should Visual Basic continue to evaluate the If statement if both conditions cannot be True?

The OrElse operator works in a similar fashion. Consider an If statement that has two conditions that are connected by an OrElse operator. For the statements of the If structure to be executed, at least one condition must evaluate to True. If the first condition evaluates to True, Visual Basic begins to execute the statements in the If structure immediately, without testing the second condition.

Here's an example of the short-circuit situation in Visual Basic, a simple routine that uses an If statement and an AndAlso operator to test two conditions and display the message “Inside If” if both conditions are True:

Dim Number As Integer = 0  If Number = 1 AndAlso MsgBox("Second condition test") Then      MsgBox("Inside If")  Else      MsgBox("Inside Else")  End If

The MsgBox function itself is used as the second conditional test, which is somewhat unusual, but the strange syntax is completely valid and gives us a perfect opportunity to see how short-circuiting works up close. The text “Second condition test” appears in a message box only if the Number variable is set to 1; otherwise, the AndAlso operator short-circuits the If statement, and the second condition isn't evaluated. If you actually try this code, remember that it's for demonstration purposes only—you wouldn't want to use MsgBox with this syntax as a test because it doesn't really test anything. But by changing the Number variable from 0 to 1 and back, you can get a good idea of how the AndAlso statement and short-circuiting work.

Here's a second example of how short-circuiting functions in Visual Basic when two conditions are evaluated using the AndAlso operator. This time, a more complex conditional test (7 / HumanAge <= 1) is used after the AndAlso operator to determine what some people call the “dog age” of a person:

Dim HumanAge As Integer  HumanAge = 7  'One year for a dog is seven years for a human  If HumanAge <> 0 AndAlso 7 / HumanAge <= 1 Then      MsgBox("You are at least one dog year old")  Else      MsgBox("You are less than one dog year old")  End If

As part of a larger program that determines the so-called dog age of a person by dividing his or her current age by 7, this bare-bones routine tries to determine whether the value in the HumanAge integer variable is at least 7. (If you haven't heard the concept of “dog age” before, bear with me—following this logic, a 28-year-old person would be four dog years old. This has been suggested as an interesting way of relating to dogs, since dogs have a lifespan of roughly one-seventh that of humans.) The code uses two If statement conditions and can be used in a variety of different contexts—I used it in the Click event procedure for a button object. The first condition checks to see whether a non-zero number has been placed in the HumanAge variable—I've assumed momentarily that the user has enough sense to place a positive age into HumanAge because a negative number would produce incorrect results. The second condition tests whether the person is at least seven years old. If both conditions evaluate to True, the message “You are at least one dog year old” is displayed in a message box. If the person is less than seven, the message “You are less than one dog year old” is displayed.

Now imagine that I've changed the value of the HumanAge variable from 7 to 0. What happens? The first If statement condition is evaluated as False by the Visual Basic compiler, and that evaluation prevents the second condition from being evaluated, thus halting, or short- circuiting, the If statement and saving us from a nasty “divide by zero” error that could result if we divided 7 by 0 (the new value of the HumanAge variable). We wouldn't have had the same luck in Visual Basic 6. Setting the HumanAge variable to 0 in Visual Basic 6 would have produced a run-time error and a crash, because the entire If statement would have been evaluated, and division by zero isn't permitted in Visual Basic 6. In Visual Studio, we get a benefit from the short-circuiting behavior.

In summary, the AndAlso and OrElse operators in Visual Basic open up a few new possibilities for Visual Basic programmers, including the potential to prevent run-time errors and other unexpected results. It's also possible to improve performance by placing conditions that are time consuming to calculate at the end of the condition statement, because Visual Basic doesn't perform these expensive condition calculations unless it's necessary. However, you need to think carefully about all the possible conditions that your If statements might encounter as variable states change during program execution.



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

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