Up to this point in the book, most of the conditional tests that you have seen involved comparing two values or expressions to see if they were equal. Although this is certainly a powerful type of test, there are times when you need to test the relationship between values and expressions in different ways. For example, you may want to know if one value is less than, greater than, or equal to another value. To accomplish these types of comparisons, you can use any of the comparison operators listed in Table 6.1.
Operator | Description |
---|---|
= | Equal |
<> | Not equal |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
To get a better feel for how to use these operators, take a look at the following example.
Dim intSecretNumber As Integer = 6 Dim intPlayerGuess As Integer intPlayerGuess = InputBox("Type a number between 1 and 10?") If intPlayerGuess < intSecretNumber Then MessageBox.Show("Your guess is too low.") End If If intPlayerGuess = intSecretNumber Then MessageBox.Show("Your guess is correct.") End If If intPlayerGuess > intSecretNumber Then MessageBox.Show("Your guess is too high.") End If
As you can see, three If…Then statements have been set up. The first If...Then statement uses the less than operator (<) to see if the value entered by the player is less than intSecretNumber (which is 6). Likewise, the second If…Then statement checks to see if the player's guess is equal to intSecretNumber. Finally, the third If…Then statement uses the greater than operator (>) to see if the number supplied by the user is greater than intSecretNumber.