You have already seen various implementations of the If…Then statement in previous chapter game projects. It is practically impossible to develop a useful application without using the If…Then statement. For example, in the Click Race game that you created in Chapter 2 "Navigating the Visual Basic 2005 Express Development Environment", you set up an If…Then statement to terminate the game's execution once 30 seconds had passed, as shown below.
If intTimerCount = 30 Then Button1.Enabled = False Button2.Enabled = False End If
In the Speed Typing game, which you created in Chapter 3, you used the If…Then statement numerous times. For example, you used five If…Then statements to determine which text statements the game should display, as shown below.
If intCount = 0 Then txtDisplay.Text = _ "Once upon a time there were three little pigs." If intCount = 1 Then txtDisplay.Text = _ "In days gone by times were hard but the people were strong." If intCount = 2 Then txtDisplay.Text = _ "Once in a while something special happens even to the " _ & "worst of people." If intCount = 3 Then txtDisplay.Text = _ "When injustice rears its head, it is the duty of all good " _ & "citizens to object." If intCount = 4 Then txtDisplay.Text = _ "It has been said that in the end there can be only one. " _ & "Let that one be Mighty Molly."
In the Lottery Assistant game that you created in Chapter 4 "Working with Menus and Toolbars", you used the If…Then statement and the cInt() conversion function to determine when a full set of lottery numbers had been selected, as shown below.
If intNoOfValidPics = CInt(txtFullSet.Text) Then blnFullSetComplete = True strDisplayString = strDisplayString & vbNewLine & vbNewLine strTestString = "_" End If
You used conditional logic extensively in the development of the Story of Mighty Molly game in Chapter 5 "Storing and Retrieving Data in Memory". For example, you used If …Then statements to validate player input, as shown below.
strColor = InputBox("What is your favorite color?", cTitleBarMsg) If strColor = "" Then MessageBox.Show("You must answer all questions to " & _ "continue.", cTitleBarMsg) End If
To better understand how If…Then statements work, take at look at the following example.
If it is below 32 degrees outside Then I'll stay in bed another hour Else I'll get up and read the newspaper EndIf
This English-like or pseudocode outline demonstrates how to apply a variation of the If …Then statements to your everyday life. In this example, the first line sets up the conditional test. If the tested condition turns out to be true, then the actions specified by the second statement are executed. Otherwise, an alternative course of action is taken.
Pseudocode is a rough, English-like outline or sketch of one or more program statements. By writing what you are trying to do in pseudocode and then translating that pseudocode into actual program statements, you can simplify application development. The pseudocode, in effect, becomes an initial-level draft version of your application.
Now that you have seen several examples of the If…Then statement in action, let's spend some time dissecting it and exploring all its variations.
The If…Then statement provides the ability to test two or more conditions and to alter program statement flow based on the outcome of those tests. The If…Then statement supports many variations, as demonstrated by the following syntax.
If condition Then statements ElseIf condition Then statements Else statements End If
Within this overall structure, there are many variations of the If…Then statements. We'll explore these variations in the sections that follow.
In its simplest form, the If…Then statement tests a single condition and performs a single command when the tested condition proves true, as demonstrated below.
Dim intCounter As Integer = 0 If intCounter = 0 Then MessageBox.Show("We have a match.")
Here the condition being tested is whether the value assigned to intCounter equals 0. If the value assigned to intCounter is equal to 0, the result of the conditional test is true and therefore the MessageBox.Show method will execute and display a message. However, if the test proves false, the MessageBox.Show method will not execute and the application continues on, processing any remaining programming statements.
The advantage of the single line If…Then statement is that it allows you to set up a simple conditional test and to perform a single action only if the test proves true. This allows you to keep your code simple and to place both the conditional test and the resulting action on the same line.
More often than not, the logic that you'll need to use when testing logical conditions will be too complicated or large to fit into a single statement. When this is the case, you'll need to use the If…Then statement in the format demonstrated below.
Dim intCounter As Integer = 0 If intCounter = 0 Then intCounter += 1 MessageBox. Show ("The value of intCounter is " & intCounter) End If
In this example, the number of commands to be executed by the If…Then statement are too numerous to be placed in a single statement. Therefore, the If…Then statement had to be expanded into a code block by adding an End If statement to the end. When used in this manner, you can place any number of statements between the opening If…Then statement and the closing End If statement, and they will all be executed if the condition being tested proves true.
The two previous examples demonstrate how to execute one or more commands when a tested condition provides true. But what do you do when the tested condition proves false, and as a result, you want to execute an alternate set of commands? One option is to write a second If…Then statement. For example, suppose you created a small Visual Basic application as depicted in Figure 6.5.
Figure 6.5: Validating player age before allowing the game to be played.
In this example, the application consists of a form with a Label, a TextBox, and a Button control. The application requires that the player types an age and clicks on the button labeled Play before being allowed to play the game. The following statements show the program code that has been added to the Button control's Click event.
Public Class Forml Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If Int32.Parse(TextBox1.Text) < 18 Then MessageBox.Show("Thanks for playing!") End If If Int32.Parse(TextBox1.Text) >= 18 Then MessageBox. Show("Sorry. You are too old to play this game!") Application.Exit() End If End Sub End Class
Trick | Int32.Parse() is a method that is used to convert a String value to an Integer value. Since, in the previous example, the TextBox control was used to collect the user's input, I converted its contents to Integer before trying to it. |
As you can see, two different If…Then statements have been set up. The first If…Then statement checks to see if the player is less than 18 years old. The second If…Then statement checks to see if the player is greater than or equal to 18 years of age. If the player is less than 18 years old a friendly greeting message is displayed. Otherwise, the player is told that he is too old and the game is terminated. Note that for this example to work correctly, the user is required to enter a numeric value. Otherwise, an error will occur. Later, in this chapter's game project, you'll see examples of how to perform input validation in order to prevent incorrect user input from causing errors.
Although these two sets of If…Then statements certainly get the job done, a better way to accomplish the same thing would be to set up an If…Then…Else statement, as demonstrated below.
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If Int32.Parse(TextBox1.Text) < 18 Then MessageBox.Show("Thanks for playing!") Else MessageBox.Show("Sorry. You are too old to play this game!") Application.Exit() End If End Sub End Class
As you can see, the If…Then…Else version of this example is slightly smaller and requires one less conditional test, making the programming logic simpler and easier to follow. Graphically, Figure 6.6 provides you with a visual flowchart view of the logic used in this example.
Figure 6.6: A flowchart showing the logic the If…Then…Else statements.
A flowchart is a graphical depiction of the logic flow in a computer application.
Professional programmers often develop flowcharts that outline the overall execution of an application that they are about to develop. This helps them by providing a visual map that lays out the application's overall design while also helping to organize the programmer's thoughts. Once the application is complete, the flowchart can also be used as supplemental documentation.
If an application is particularly large, a team of programmers, each of whom is assigned to work on a particular part of the application, may develop it. Using a flowchart, the team of programmers could divide up the work by each focusing on specific sections of the application as outlined in the flowchart.
If you wish, you can add the ElseIf keyword one or more times to expand the If…Then statement. Each instance of the ElseIf keyword allows you to set up a test for another alternative condition. To better understand how the If…Then…ElseIf statement works, take a look at the following example, shown in Figure 6.7.
Figure 6.7: Using an If…Then…ElseIf statement to process the contents of a ComboBox control.
In this example, a new Visual Basic application has been created, consisting of a farm with a Label, a Button, and a ComboBox control.
Trick | The ComboBox control provides a drop-down List from which the user can select a single option. After adding a ComboBox to a form at design time, you can populate it with choices by locating its Items property in the Properties window and clicking on the (Collection) entry in the value column. This opens the String Collection Editor, as shown in Figure 6.8. All you have to do now is enter the choices that you want to display in the ComboBox control, making sure to type each option on its own line. |
To make a selection, the user must select one of the choices displayed in the ComboBox control and then click on the form's Button control. When this occurs, the code assigned to this control's Click event, shown below, will execute.
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If ComboBox1.Text = "1 - 12" Then MessageBox.Show("There is a skateboard park just " & _ "down the street.") ElseIf ComboBox1. Text = "13 - 18" Then MessageBox.Show("There is a 99 cent movie theater " & _ "2 blocks over.") ElseIf ComboBox1.Text = "19 - 21" Then MessageBox.Show("A new dance club has opened downtown " & _ "on 3rd street.") Else MessageBox.Show ("OH, You must be tired. How about a nap.") End If End Sub End Class
As you can see, by adding multiple ElseIf keywords, you are able to set up a conditional logic that can test for multiple possible conditions.