THE IF THEN STATEMENT


THE IF THEN STATEMENT

You have already seen various implementations of the IfThen statement in previous chapter game projects. It is practically impossible to develop a useful application without using the IfThen 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 IfThen 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 IfThen statement numerous times. For example, you used five IfThen 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 IfThen 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 IfThen 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.

image from book
DEFINITION

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.

image from book

Now that you have seen several examples of the IfThen statement in action, let's spend some time dissecting it and exploring all its variations.

IfThen Statement Syntax

The IfThen statement provides the ability to test two or more conditions and to alter program statement flow based on the outcome of those tests. The IfThen 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 IfThen statements. We'll explore these variations in the sections that follow.

The Single Line IfThen Statement

In its simplest form, the IfThen 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 IfThen 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.

Multiline IfThen Statements

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 IfThen 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 IfThen statement are too numerous to be placed in a single statement. Therefore, the IfThen 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 IfThen statement and the closing End If statement, and they will all be executed if the condition being tested proves true.

The IfThenElse Statement

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 IfThen statement. For example, suppose you created a small Visual Basic application as depicted in Figure 6.5.

image from book
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 IfThen statements have been set up. The first IfThen statement checks to see if the player is less than 18 years old. The second IfThen 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 IfThen statements certainly get the job done, a better way to accomplish the same thing would be to set up an IfThenElse 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 IfThenElse 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.

image from book
Figure 6.6: A flowchart showing the logic the IfThenElse statements.

image from book
DEFINITION

A flowchart is a graphical depiction of the logic flow in a computer application.

image from book

image from book
IN THE REAL WORLD

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.

image from book

The IfThenElself Statement

If you wish, you can add the ElseIf keyword one or more times to expand the IfThen statement. Each instance of the ElseIf keyword allows you to set up a test for another alternative condition. To better understand how the IfThenElseIf statement works, take a look at the following example, shown in Figure 6.7.

image from book
Figure 6.7: Using an IfThenElseIf 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.

image from book
Figure 6.8: Using the String Collection Editor at design time to populate the contents of a ComboBox control.

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.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

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