October 24, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Discovering Visual Basic .NET: Making Decisions

  • January 10, 2005
  • By Bill Hatfield
  • Send Email »
  • More Articles »

Creating a Compound If...Then

You can also use what programmer-types like to call a logical expression in an If...Then condition. This simply means that you can put more than one question together inside the same condition by using an And or an Or to separate them. This creates a compound If...Then statement.

A compound If...Then statement works just like you may expect. If an And separates the two conditions, the statement succeeds only if both conditions are true. If either one or both is false, the statement portion is ignored. If an Or separates the two conditions, the statement succeeds if either condition (or both) is true.

You can connect together as many conditions as you like as long as an And or an Or separates each condition from the others:

If Temperature <= 32 And Liquid = "Water" Then   Console.WriteLine("Looks like ice...")End If

Of course, too many conditions can make your statement very confusing. When you're writing programs, one rule always applies: As much as possible, keep it simple!

As I Was Saying: Line Continuation

This section is a quick digression on a topic that doesn't directly have anything to do with conditions, but can be useful when your lines get really long (whether the line is an If...Then statement or not).

You can break your line in two without confusing VB.NET into thinking it's supposed to treat that code as two separate lines. Here's an example:

 If Weekday(Today) > 3 And   _ Weekday(Today) < 6Then

You find the underscore character ( _ ) on your keyboard on the same key as the dashjust press Shift along with it. The underscore at the end of the line tells the VB.NET to consider the next line as an extension of this one.

Although you may often use the underscore with a compound If...Then, that's not the only place. In fact, you can use it in any statement. Just place the underscore in the line just before you break it. You can break a line anywhere you'd normally put a space.

If you use the underscore, indent the second line three spaces or so to make it clear that the second line is a continuation of the previous line.

In some cases, you may want to break a long string and put part of it on a second line. You can use the underscore character to do that, too, but you also need to use the & concatenation character with it:

Desc = "This is a " & _   "long description."

You put a final quote at the end of the string on the first line and a new string with quotes around it on the second line. You still need the underscore, but you also need the & to join the two strings together.

What to Do if It Isn't True

In the previous sections of this article, all the If....Then statements only tell the computer what to do if a condition is true. What if you want it to do something else when the condition is not true? That's where Else comes in:

Imports SystemImports Microsoft.VisualBasicModule PassFail   Public Sub Main()      Dim Grade As Integer      Randomize      Grade = Int(Rnd * 100) + 1 ' Random - between 1 and 100      Console.WriteLine("Your grade is " & Grade)      If Grade >= 60 Then         Console.WriteLine("You passed!")      Else         Console.WriteLine("You failed...")      End If   End SubEnd Module

Run this program several times until you see both passing and failing results.

Handling Multiple Conditions

You can ask one question; why not more? Of course, you can always just write one If...Then statement after another. For example, if you want to translate a percentage grade to a letter grade, you may write code that looks like this:

Imports SystemImports Microsoft.VisualBasicModule PercentageToLetter   Public Sub Main()      Dim Grade As Integer      Dim LetterGrade As String      Randomize      Grade = Int(Rnd * 100) + 1    ' Random - between 1 and 100      Console.WriteLine("Your grade is " & Grade)      If Grade >= 90 Then         LetterGrade = "A"         Console.WriteLine("You got an A! Congratulations.")      End If      If Grade >= 80 And Grade < 90 Then         LetterGrade = "B"         Console.WriteLine("You got a B. Good job.")      End If      If Grade >= 70 And Grade < 80 Then         LetterGrade = "C"         Console.WriteLine("You got a C. Not bad.")      End If      If Grade >= 60 And Grade < 70 Then         LetterGrade = "D"         Console.WriteLine("You got a D. Try harder...")      End If      If Grade < 60 Then         LetterGrade = "F"         Console.WriteLine("You failed. I'm sorry.")      End If   End SubEnd Module

The preceding code works fine. But it has a couple of big problems: It's wordy, and you end up repeating yourself a lot. To make the process easier, VB.NET includes another statement to help you in situations like this: ElseIf. If you use ElseIf, your program begins to look simpler and is easier to understand:

Imports SystemImports Microsoft.VisualBasicModule PercentageToLetter   Public Sub Main()      Dim Grade As Integer      Dim LetterGrade As String      Randomize      Grade = Int(Rnd * 100) + 1    ' Random - between 1 and 100      Console.WriteLine("Your grade is " & Grade)      If Grade >= 90 Then         LetterGrade = "A"         Console.WriteLine("You got an A! Congratulations.")      ElseIf Grade >= 80 Then         LetterGrade = "B"         Console.WriteLine("You got a B. Good job.")      ElseIf Grade >= 70 Then         LetterGrade = "C"         Console.WriteLine("You got a C. Not bad.")      ElseIf Grade >= 60 Then         LetterGrade = "D"         Console.WriteLine("You got a D. Try harder...")      Else         LetterGrade = "F"         Console.WriteLine("You failed. I'm sorry.")      End If   End SubEnd Module

Now the whole thing is part of one big, long If...Then. You know that because the code has only one End Ifall the way at the end.

Here's the way this If...Then...ElseIf works:

  1. If the Grade is greater than or equal to 90, the LetterGrade variable is set to A, the user is informed, and then the statement ends. The rest of the conditions are ignored after a condition is met.
  2. If the first condition is false, the second condition is checked. Here, you only have to check whether the Grade is 80 or better. You don't have to specify that it is less than 90 because if it had been 90 or greater, you wouldn't be executing this condition. Right?
  3. Likewise for the third and fourth conditions.
  4. If you get through all the conditions and you still don't have a match, the Else catches everything else—which, in this case, is bad news.




Page 3 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel