Conditional Operators

To control the program flow, we can use conditional operators. Conditional operators are very powerful tools, they let the VB program compare data values and then decide what action to take.

Operator Meaning
= Equal to
> Greater than
< Less Than
>= Greater than or equal to
<= Less than or equal to
<> Not Equal to
 
  • Take care with reading the equals sign in Visual Basic.  It has two different meanings:  one is to compare, the other is to assign.  It is comparing when used in an if...then statement.  
    For example  If txtGuess.Text = RandNo Then ...
    It is assigning the value of RandNo to txtGuess.text if used in the format
    txtGuess.Text=RandNo

  • You can also compare strings with the above operators. However, there are certain rules to follow: Upper case letters are less than lowercase letters, "A"<"B"......<"Z"<"a"<"b".......<"z"  and numbers are less than letters.    

Logical Operators

As well as conditional operators, there are a few logical operators which offer added power to your programs. 

Operator Meaning
And Both sides must be true
or One side or other must be true
Xor One side or other must be true but not both
Not Negates truth

This table summarises the results of using logical operators: 

Statement A might be Age>7, Statement B might be Sex = "F".

We could have a line in our program that says:

If Age > 7 AND Sex="F" then....

If Age>7 OR Sex ="F" then....

If Age>7 XOR Sex ="F" then....

If NOT Age>7 then ....

Statement A

Statement B

A AND B A OR B A XOR B NOT A
True True True True False False
True False False True True False
False True False True True True
False False False False False True

Click here for more on Boolean expressions. 


Using Conditional and Logical Operators to Control Program Flow

We can use if...then...else statements together with conditional or logical operators to control program flow.  You can either put the entire if..then...else statement on the same line, or you can use a blocked if statement. 

  • If ... then...else

If userAge < 20 then msgBox("Cool... let's have some fun!") else _
       msgBox("Don't you think you're a bit old for this sort of thing!")

  • Blocked if statements

If condition-1 Then
statements

ElseIf condition-2 Then
elseifstatements ...

Else
elsestatements

End If

Notes: If/Then must be on the same line, Must finish with End If, ElseIf/Then must be on same line


Guessing Game

We are going to use the If...then...else blocked statement to make a guessing game.  The computer will generate a random number between 1 and 100 and the player must guess the number.

Design the Interface

Design an interface with these things on it:

Note: The lblMessage label should have no caption.

Name your form: frmGame


Write the Code

  • First of all we will declare a variable RandNo to store the random number in.  We will not declare it inside any particular procedure, because we want to use it in several procedures.  We will put it in the general declarations section: (Go to the code window F7, choose General from the top left drop down box)

  • When the user clicks on the cmdStart button, we want to generate a random number and make the lblMessage caption and txtMessage text blank.  Here is the code we need:
Private Sub cmdStart_Click()
     Randomize
     RandNo = Int(Rnd * 100) + 1
     lblMessage.Caption = ""
     txtGuess.Text = ""
End Sub

 

  • When the user clicks on the cmdExit button, we want to end the program:
Private Sub cmdExit_Click()
     Unload Me
End Sub

 

  • After the user enters their guess, they click on the cmdGuess button.  If the guess equals the random number, then the lblMessage caption becomes "You guessed it!" or if the guess is too low, it becomes "Too Low", otherwise the guess must be too high, so it becomes "Too High"
Private Sub cmdGuess_Click()
      If val(txtGuess.Text) = RandNo Then
                  lblMessage.Caption = "You guessed it!"
            ElseIf val(txtGuess.Text) < RandNo Then
                  lblMessage.Caption = "Too Low"
            Else: lblMessage.Caption = "Too High"
      End If
End Sub

 

Each property of a control is associated with a particular data type.  The text property of a text box has the data type String.  So when this property is used in calculations it is necessary to use Val to convert the value to a numeric data type.  That is why we see the function Val in the code  eg val(txtGuess.text)  Any non numeric data is converted to 0 by the val function.

Test it

Test your program and make any necessary adjustments.  

1. Add in an image of a star (or something else) that appears when the user has guessed the correct answer.

2. Modify the game to keep a tally of how many guesses it takes the user.  

3. Modify the game so that 2 players can play it - the first to guess the number will be the winner. 

 

Using the val function provides some protection against the entry of invalid data in the text box.

An improved technique for this would be the use of the IsNumeric function.  This function returns a value of True or False depending on whether its argument can be converted to a number or not.

For example, IsNumeric(txtGuess.txt) would have the value true if the text property of txtGuess can be converted to a number.  

So you can modify the code to pop up a message box if an invalid value is entered:

If IsNumeric(txtGuess.Text) = False  Then
    MsgBox "Please enter a number", 48, "Error"
elseif.....