Home

Conditional Statements

 

Comparison Operators

 

Introduction

The essence of computer programming relies on telling the computer what to do when something occurs, and how to do it. This is performed by setting conditions, examining them and stating what decisions the computer should make.

VBasic uses various conditional statements for almost any situation your computer can encounter. As the application developer, it is up to you to anticipate these situations and make your program act accordingly.

 

The Boolean Data Type

A Boolean variable is one whose value can be either True or False. To declare such a variable, use the Boolean keyword. Here is an example:

Sub Main()
    Dim IsMarried As Boolean
End Sub
 

By default, a Boolean variable is initialized with False. If you want, you can otherwise initialize it with a True value. After declaring a Boolean variable, you can use it to test its value and to involve it in other conditional statements.

To convert a value to Boolean, you can use CBool().

  

Equality =

To compare two variables for equality, use the = operator. Its syntax is:

Value1 = Value2

The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the value of Value1 would be compared with the value of Value2. If Value1 and Value2 hold the same value, the comparison produces a True result. If they are different, the comparison renders false or 0.

The comparison for equality

Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim IsFullTime As Boolean

        Console.WriteLine("Is Employee Full Time? {0}", IsFullTime)

        IsFullTime = True
        Console.WriteLine("Is Employee Full Time? {0}", IsFullTime)
    End Sub

End Module

This would produce:

Is Employee Full Time? False
Is Employee Full Time? True

 

Inequality <>

As opposed to checking for equality, you may instead want to know whether two values are different. The operator used to perform this comparison is <> and its formula is:

Variable1 <> Variable2

 

The comparison for inequality

If the operands on both sides of the operator are the same, the comparison renders false. If both operands hold different values, then the comparison produces a true result. This also shows that the equality = and the inequality <> operators are opposite.

 

A Lower Value <

To find out whether one value is lower than another, use the < operator. Its syntax is:

Value1 < Value2

The value held by Value1 is compared to that of Value2. As it would be done with other operations, the comparison can be made between two variables, as in Variable1 < Variable2. If the value held by Variable1 is lower than that of Variable2, the comparison produces a True.

 

Flowchart: Less Than

Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim PartTimeSalary, ContractorSalary As Double
        Dim IsLower As Boolean

        PartTimeSalary = 20.15
        ContractorSalary = 22.48
        IsLower = PartTimeSalary < ContractorSalary

        Console.WriteLine("Part Time Salary:  {0}", PartTimeSalary)
        Console.WriteLine("Contractor Salary: {0}", ContractorSalary)
        Console.WriteLine("Is PartTimeSalary < ContractorSalary? {0}", IsLower)

        PartTimeSalary = 25.55
        ContractorSalary = 12.68
        IsLower = PartTimeSalary < ContractorSalary

        Console.WriteLine()
        Console.WriteLine("Part Time Salary:  {0}", PartTimeSalary)
        Console.WriteLine("Contractor Salary: {0}", ContractorSalary)
        Console.WriteLine("Is PartTimeSalary < ContractorSalary? {0}", IsLower)

        Console.WriteLine()
    End Sub

End Module

This would produce:

Part Time Salary:  20.15
Contractor Salary: 22.48
Is PartTimeSalary < ContractorSalary? True

Part Time Salary:  25.55
Contractor Salary: 12.68
Is PartTimeSalary < ContractorSalary? False

 

 

Equality and Lower Value <=

The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is:

Value1 <= Value2

The <= operation performs a comparison as any of the last two. If both Value1 and VBalue2 hold the same value, result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true:

Less than or equal to
 

Greater Value >

When two values of the same type are distinct, one of them is usually higher than the other. VBasic provides a logical operator that allows you to find out if one of two values is greater than the other. The operator used for this operation uses the > symbol. Its syntax is:

Value1 > Value2

Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a True value. Otherwise, the comparison renders False or null.

 

Greater Than

Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim PartTimeSalary, ContractorSalary As Double
        Dim IsLower As Boolean

        PartTimeSalary = 20.15
        ContractorSalary = 22.48
        IsLower = PartTimeSalary > ContractorSalary

        Console.WriteLine("Part Time Salary:  {0}", PartTimeSalary)
        Console.WriteLine("Contractor Salary: {0}", ContractorSalary)
        Console.WriteLine("Is PartTimeSalary > ContractorSalary? {0}", IsLower)

        PartTimeSalary = 25.55
        ContractorSalary = 12.68
        IsLower = PartTimeSalary > ContractorSalary

        Console.WriteLine()
        Console.WriteLine("Part Time Salary:  {0}", PartTimeSalary)
        Console.WriteLine("Contractor Salary: {0}", ContractorSalary)
        Console.WriteLine("Is PartTimeSalary > ContractorSalary? {0}", IsLower)

        Console.WriteLine()
    End Sub

End Module

This would produce:

Part Time Salary:  20.15
Contractor Salary: 22.48
Is PartTimeSalary > ContractorSalary? False

Part Time Salary:  25.55
Contractor Salary: 12.68
Is PartTimeSalary > ContractorSalary? True

 

Greater or Equal Value >=

The greater than or the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is:

Value1 >= Value2

A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a True value. If the value of the left operand is greater than that of the right operand, the comparison still produces True. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a False result.

 

Greater Than Or Equal
 

Condition Checking

 

Introduction

In some programming assignments, you must find out whether a given situation bears a valid value. This is done by checking a condition. To support this, VBasic provides a series of words that can be combined to perform this checking. Checking a condition usually produces a True or a False result. Once the condition has been checked, you can use the result (as True or False) to take action. Because there are different ways to check a condition, there are also different types of keywords to check different things. To use them, you must be aware of what each does or cannot do so you would select the right one.

 

Practical LearningPractical Learning: Introducing Conditional Statements

  1. Start Notepad and type the following in the empty file
     
    Imports System
    
    Module Module1
        Sub Main()
    
            Dim FirstName As String, LastName As String
    	
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Application ---")
    	Console.Write("First Name: ")
    	FirstName = Console.ReadLine()
    	Console.Write("Last Name:  ")
    	LastName = Console.ReadLine()
    
    	Console.WriteLine()
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Information ---")
    	Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
    	Console.WriteLine()
        End Sub
    
    End Module
  2. To save the file, on the main menu, click File -> Save
  3. Locate and select your VBasic folder to display it in the Save In combo box
  4. Click the Create New Folder button
  5. Create a folder named MVA1 and display it in the Save In combo box
  6. Save the file as Exercise.vb
  7. Open the Command Prompt and switch to the folder that contains the above Exercise.vb file
  8. To compile the exercise, type vbc Exercise.vb and press Enter
  9. To execute the exercise, type Exercise
     
  10. Return to Notepad
 

The If...Then Statement

The If...Then statement examines the truthfulness of an expression. Structurally, its formula is:

If ConditionToCheck Then Statement

Therefore, the program examines a condition, in this case ConditionToCheck. This ConditionToCheck can be a simple expression or a combination of expressions. If the ConditionToCheck is true, then the program will execute the Statement.

There are two ways you can use the If...Then statement. If the conditional formula is short enough, you can write it on one line, like this:

If ConditionToCheck Then Statement

Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim IsMarried As Boolean
        Dim TaxRate As Double

        Console.WriteLine("Tax Rate: {0:F}", TaxRate)

        IsMarried = True
        If IsMarried Then TaxRate = 30.65

        Console.WriteLine("Tax Rate: {0:F}", TaxRate)
    End Sub

End Module

This would produce:

Tax Rate: 0.00
Tax Rate: 30.65
Press any key to continue

If there are many statements to execute as a truthful result of the condition, you should write the statements on alternate lines. Of course, you can use this technique even if the condition you are examining is short. In this case, one very important rule to keep is to terminate the conditional statement with End If. The formula used is:

If ConditionToCheck Then
    Statement
End If

Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim IsMarried As Boolean
        Dim TaxRate As Double

        Console.WriteLine("Tax Rate: {0:F}", TaxRate)

        IsMarried = True
        If IsMarried Then
            TaxRate = 30.65
            Console.WriteLine("Tax Rate: {0:F}", TaxRate)
        End If
    End Sub

End Module
 
 

Practical LearningPractical Learning: Using if

  1. To state an if condition, change the program as follows:
     
    Imports System
    
    Module Module1
    
        Sub Main()
            Dim FirstName As String, LastName As String
    	Dim OrganDonorAnswer As String
    	
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Application ---")
    	Console.Write("First Name: ")
    	FirstName = Console.ReadLine()
    	Console.Write("Last Name:  ")
    	LastName = Console.ReadLine()
    	Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
    	OrganDonorAnswer = Console.ReadLine()
    
    	Console.WriteLine()
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Information ---")
    	Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
    	Console.Write("Organ Donor? ")
    	if OrganDonorAnswer = "1" Then Console.WriteLine("Yes")
    	Console.WriteLine()
        End Sub
    
    End Module
  2. Save it and switch to the Command Prompt to test it. Here is an example:
     
    C:\VBasic\MVA1>vbc Exercise.vb
    Microsoft (R) Visual Basic .NET Compiler version 7.10.3052.4
    for Microsoft (R) .NET Framework version 1.1.4322.573
    Copyright (C) Microsoft Corporation 1987-2002. All rights reserved.
    
    
    C:\VBasic\MVA1>Exercise
     -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Ernestine
    Last Name:  Ardant
    Are you willing to be an Organ Donor(1=Yes/0=No)? 1
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name: Ernestine Ardant
    Organ Donor? Yes
  3. Return to Notepad

The If...Then...Else Statement

The If...Then statement offers only one alternative: to act if the condition is true. Whenever you would like to apply an alternate expression in case the condition is false, you can use the If...Then...Else statement. The formula of this statement is:

If ConditionToCheck Then
    Statement1
Else
    Statement2
End If

When this section of code is executed, if the ConditionToCheck is true, then the first statement, Statement1, is executed. If the ConditionToCheck is false, the second statement, in this case Statement2, is executed.

Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim MemberAge As Int16
        Dim MemberCategory As String

        MemberAge = 16

        If MemberAge <= 18 Then
            MemberCategory = "Teen"
        Else
            MemberCategory = "Adult"
        End If

        Console.WriteLine("Membership: {0}", MemberCategory)
    End Sub

End Module

This would produce:

Membership: Teen

 

 

Practical LearningPractical Learning: Using if...else

  1. Make the following changes to the file:
     
    Imports System
    
    Module Module1
    
        Sub Main()
            	Dim FirstName As String, LastName As String
    	Dim OrganDonorAnswer As String
    	Dim Sex As Char
    	
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Application ---")
    	Console.Write("First Name: ")
    	FirstName = Console.ReadLine()
    	Console.Write("Last Name:  ")
    	LastName = Console.ReadLine()
    	Console.Write("Sex(F=Female/M=Male): ")
    	Sex = char.Parse(Console.ReadLine())
    	Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
    	OrganDonorAnswer = Console.ReadLine()
    
    	Console.WriteLine()
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Information ---")
    	Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
    	Console.WriteLine("Sex:         {0}", Sex)
    	Console.Write("Organ Donor? ")
    	if OrganDonorAnswer = "1" Then
    	    Console.WriteLine("Yes")
            	Else
    	    Console.WriteLine("No")
    	End If
    
    	Console.WriteLine()
        End Sub
    
    End Module
  2. Save the file and switch to the Command Prompt
  3. Compile and test the file twice, once with 1 to the question, then with 0 to the last question
  4. Return to Notepad
 

The If...Then...ElseIf Statement

The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it offers as many choices as necessary. The formula is:

If Condition1 Then
    Statement1
ElseIf Condition2 Then
    Statement2
ElseIf Conditionk Then
    Statementk
End If

The program will first examine Condition1. If Condition1 is true, the program will execute Statment1 and stop examining conditions. If Condition1 is false, the program will examine Condition2 and act accordingly. Whenever a condition is false, the program will continue examining the conditions until it finds one. Once a true condition has been found and its statement executed, the program will terminate the conditional examination at End If. Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim MemberAge As Int16
        Dim MemberCategory As String

        MemberAge = 32

        If MemberAge <= 18 Then
            MemberCategory = "Teen"
        ElseIf MemberAge < 55 Then
            MemberCategory = "Adult"
        End If

        Console.WriteLine("Membership: {0}", MemberCategory)
    End Sub

End Module

This would produce;

Membership: Adult

There is still a possibility that none of the stated conditions is true. In this case, you should provide a "catch all" condition. This is done with a last Else section. The Else section must be the last in the list of conditions and would act if none of the primary conditions is true. The formula to use would be:

If Condition1 Then
    Statement1
ElseIf Condition2 Then
    Statement2
ElseIf Conditionk Then
    Statementk
Else
    CatchAllStatement
End If

Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim MemberAge As Int16
        Dim MemberCategory As String

        MemberAge = 62

        If MemberAge <= 18 Then
            MemberCategory = "Teen"
        ElseIf MemberAge < 55 Then
            MemberCategory = "Adult"
        Else
            MemberCategory = "Senior"
        End If

        Console.WriteLine("Membership: {0}", MemberCategory)
    End Sub

End Module

This would produce:

Membership: Senior

 

 

Practical LearningPractical Learning: Using if...else if

  1. Change the file as follows:
     
    Imports System
    
    Module Module1
    
        Sub Main()
    	Dim FirstName As String, LastName As String
    	Dim OrganDonorAnswer As String
    	Dim Sex As Char, Gender As String
    	
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Application ---")
    	Console.Write("First Name: ")
    	FirstName = Console.ReadLine()
    	Console.Write("Last Name:  ")
    	LastName = Console.ReadLine()
    	Console.Write("Sex(F=Female/M=Male): ")
    	Sex = char.Parse(Console.ReadLine())
    	Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
    	OrganDonorAnswer = Console.ReadLine()
    
    	if Sex = "f" Then
    	    Gender = "Female"
    	ElseIf Sex = "F" Then
    	    Gender = "Female"
    	ElseIf Sex = "m" Then
    	    Gender = "Male"
    	ElseIf Sex = "M" Then
    	    Gender = "Male"
    	else
    	    Gender = "Unknown"
    	End If
    
    	Console.WriteLine()
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Information ---")
    	Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
    	Console.WriteLine("Sex:         {0}", Gender)
    	Console.Write("Organ Donor? ")
    	if OrganDonorAnswer = "1" Then
    	    Console.WriteLine("Yes")
            	Else
    	    Console.WriteLine("No")
    	End If
    
    	Console.WriteLine()
        End Sub
    
    End Module
  2. Save, compile, and test the file. Here is an example:
     
    C:\VBasic\MVA1>vbc Exercise.vb
    Microsoft (R) Visual Basic .NET Compiler version 7.10.3052.4
    for Microsoft (R) .NET Framework version 1.1.4322.573
    Copyright (C) Microsoft Corporation 1987-2002. All rights reserved.
    
    
    C:\VBasic\MVA1>Exercise
     -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Ernestine
    Last Name:  Zola
    Sex(F=Female/M=Male): f
    Are you willing to be an Organ Donor(1=Yes/0=No)? 0
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name: Ernestine Zola
    Sex:         Female
    Organ Donor? No
  3. Return to Notepad
 

The Select Case Statement

If you have a large number of conditions to examine, the If...Then...Else will go through each one of them. VBasic offers the alternative of jumping to the statement that applies to the state of the condition.

The formula of the Select Case is:

Select Case Expression
    Case Expression1
        Statement1
    Case Expression2
        Statement2
    Case Expressionk
        Statementk
End Select

The Expression will examined and evaluated once. Then it will compare the result of this examination with the Expression of each case. Once it finds one that matches, it would execute the corresponding Statement. Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim Answer As Byte

        Console.WriteLine("One of the following is not a VBasic keyword")
        Console.WriteLine("1) Function")
        Console.WriteLine("2) Except")
        Console.WriteLine("3) ByRef")
        Console.WriteLine("4) Each")
        Console.Write("Your Answer? ")
        Answer = Console.ReadLine()

        Select Case Answer
            Case 1
                Console.WriteLine("Wrong: Function is a VBasic keyword.")
                Console.WriteLine("It is used to create a procedure of a function type")
            Case 2
                Console.WriteLine("Correct: Except is not a keyword in VBasic ")
                Console.WriteLine("but __except is a C++ keyword used in Exception Handling")
            Case 3
                Console.WriteLine("Wrong: ByRef is a VBasic keyword used to pass an ")
                Console.WriteLine("argument by reference to a procedure")
            Case 4
                Console.WriteLine("Wrong: The ""Each"" keyword is used in VBasic in a type ")
                Console.WriteLine("of looping used to ""scan"" a list of item.")
        End Select

        Console.WriteLine()
    End Sub

End Module

Here is an example of running the program:

One of the following is not a VBasic keyword
1) Function
2) Except
3) ByRef
4) Each
Your Answer? 2
Correct: Except is not a keyword in VBasic
but __except is a C++ keyword used in Exception Handling

If you anticipate that there could be no match between the Expression and one of the Expressions, you can use a Case Else statement at the end of the list. The statement would then look like this:

Select Case Expression
    Case Expression1
        Statement1
    Case Expression2
        Statement2
    Case Expressionk
        Statementk
    Case Else
        Statementk
End Select

Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim Answer As Byte

        Console.WriteLine("One of the following is not a VBasic keyword")
        Console.WriteLine("1) Function")
        Console.WriteLine("2) Except")
        Console.WriteLine("3) ByRef")
        Console.WriteLine("4) Each")
        Console.Write("Your Answer? ")
        Answer = Console.ReadLine()

        Select Case Answer
            Case 1
                Console.WriteLine("Wrong: Function is a VBasic keyword.")
                Console.WriteLine("It is used to create a procedure of a function type")
            Case 2
                Console.WriteLine("Correct: Except is not a keyword in VBasic ")
                Console.WriteLine("but __except is a C++ keyword used in Exception Handling")
            Case 3
                Console.WriteLine("Wrong: ByRef is a VBasic keyword used to pass an ")
                Console.WriteLine("argument by reference to a procedure")
            Case 4
                Console.WriteLine("Wrong: The ""Each"" keyword is used in VBasic in a type ")
                Console.WriteLine("of looping used to ""scan"" a list of item.")
            Case Else
                Console.WriteLine("Invalid Selection")
        End Select

        Console.WriteLine()
    End Sub

End Module

Here is an example of running the program:

One of the following is not a VBasic keyword
1) Function
2) Except
3) ByRef
4) Each
Your Answer? 8
Invalid Selection

Instead of using one value for a case, you can apply more than one. To do this, on the right side of the Case keyword, separate the expressions with commas. You can also use a range of value for a case. To do this, on the right side of Case, enter the lower value, followed by To, followed by the higher value. Here is an example:

Imports System

Module Module1

    Sub Main()
        Dim age As Integer
        age = 24

        Select Case age
            Case 0 To 17
                Console.WriteLine("Teen")
            Case 18 To 55
                Console.WriteLine("Adult")
            Case Else
                Console.WriteLine("Senior")
        End Select
    End Sub

End Module

 

 

Practical LearningPractical Learning: Using Select...Case

  1. Change the file as follows:
     
    Imports System
    
    Module Module1
    
        Sub Main()
    	Dim FirstName As String, LastName As String
    	Dim OrganDonorAnswer As String
    	Dim Sex As Char, Gender As String
    	Dim DLClass As String
    	
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Application ---")
    	Console.Write("First Name: ")
    	FirstName = Console.ReadLine()
    	Console.Write("Last Name:  ")
    	LastName = Console.ReadLine()
    	Console.Write("Sex(F=Female/M=Male): ")
    	Sex = char.Parse(Console.ReadLine())
    	Console.WriteLine(" - Driver's License Class -")
    	Console.WriteLine("A - All Non-commercial vehicles except motorcycles")
    	Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs.")
    	Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.")
    	Console.WriteLine("K - Mopeds")
    	Console.WriteLine("M - Motorcycles")
    	Console.Write("Your Choice: ")
    	DLClass = char.Parse(Console.ReadLine())
    	Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
    	OrganDonorAnswer = Console.ReadLine()
    
    	if Sex = "f" Then
    	    Gender = "Female"
    	ElseIf Sex = "F" Then
    	    Gender = "Female"
    	ElseIf Sex = "m" Then
    	    Gender = "Male"
    	ElseIf Sex = "M" Then
    	    Gender = "Male"
    	else
    	    Gender = "Unknown"
    	End If
    
    	Console.WriteLine()
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Information ---")
    	Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
    	Console.WriteLine("Sex:         {0}", Gender)
    
    	Select Case DLClass
    	case "a", "A"
    	    Console.WriteLine("Class:       A")
    	case "b", "B"
    	    Console.WriteLine("Class:       B")
    	case "c", "C"
    	    Console.WriteLine("Class:       C")
    	case "k", "K"
    	    Console.WriteLine("Class:       K")
    	case "m", "M"
    	    Console.WriteLine("Class:       M")
    	Case Else
    	    Console.WriteLine("Class:       Unknown")
    	End Select
    
    	Console.Write("Organ Donor? ")
    	if OrganDonorAnswer = "1" Then
    	    Console.WriteLine("Yes")
            ElseIf OrganDonorAnswer = "0" Then
    	    Console.WriteLine("No")
    	Else
    	    Console.WriteLine("N/A")
    	End If
    
    	Console.WriteLine()
        End Sub
    
    End Module
  2. Save, compile, and test the application. Here is an example:
     
    C:\VBasic\MVA1>vbc Exercise.vb
    Microsoft (R) Visual Basic .NET Compiler version 7.10.3052.4
    for Microsoft (R) .NET Framework version 1.1.4322.573
    Copyright (C) Microsoft Corporation 1987-2002. All rights reserved.
    
    
    C:\VBasic\MVA1>Exercise
     -=- Motor Vehicle Administration -=-
     --- Driver's License Application ---
    First Name: Paul
    Last Name:  Dock
    Sex(F=Female/M=Male): M
     - Driver's License Class -
    A - All Non-commercial vehicles except motorcycles
    B - Non-commercial vehicles up to and including 26,001/more lbs.
    C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.
    K - Mopeds
    M - Motorcycles
    Your Choice: c
    Are you willing to be an Organ Donor(1=Yes/0=No)? 1
    
     -=- Motor Vehicle Administration -=-
     --- Driver's License Information ---
    Full Name: Paul Dock
    Sex:         Male
    Class:       C
    Organ Donor? Yes
    
    
    C:\VBasic\MVA1>
  3. Return to Notepad

 

Enumerators

An enumeration is a list of values with each represented by a name. Enumerations are highly useful in conditional statements because they allow using recognizable names to identify confusing values.

To create an enumeration, use the Enum keyword followed by a name. The creation of an enumeration must end with End Enum:

Enum MembershipType

End Enum

Between the Enum Name and the End Enum lines, you can enter the values of the enumerations, also called members of the enumeration. Each member must be on its own line. Here is an example:

Enum MembershipType
    Teen
    Adult
    Senior
End Enum

Each member of the enumeration holds a value of a natural number, such as 0, 4, 12, 25, etc. After creating an enumeration, you can declare a variable from it. For example, you can declare a variable of a MembershipType type as follows:

Imports System

Module Module1
    Enum MembershipType
        Teen
        Adult
        Senior
    End Enum

    Sub Main()
        Dim MType As MembershipType
    End Sub

End Module

After declaring such a variable, to initialize it, specify which member of the enumeration would be given to it. You should only assign a known member of the enumeration. To do this, on the right side of the assignment operator, type the name of the enumeration, followed by the period operator, and followed by the member whose value you want to assign. Here is an example:

Imports System

Module Module1
    Enum MembershipType
        Teen
        Adult
        Senior
    End Enum

    Sub Main()
        Dim MType As MembershipType

        MType = MembershipType.Senior
    End Sub

End Module

You can also find out what value the declared variable is currently holding. For example, you can display it on the console using Write() or WriteLine(). Here is an example:

Imports System

Module Module1
    Enum MembershipType
        Teen
        Adult
        Senior
    End Enum

    Sub Main()
        Dim MType As MembershipType

        MType = MembershipType.Senior
        Console.WriteLine("Membership Type: " & MType)
    End Sub

End Module

This would produce:

Membership Type: 2

As seen on this example, an enumeration is in fact a list of numbers where each member of the list is identified with a name. By default, the first item of the list has a value of 0, the second has a value of 1, etc. Based on this, on the MembershipType enumerator, Teen has a value of 0 while Senior has a value of 2. These are the default values. If you don't want these values, you can explicitly define the value of one or each member of the list. Suppose you want the Teen member in the above enumeration to have a value of 5. To do this, use the assignment operator "=" to give the desired value. The enumerator would be:

Enum MembershipType
    Teen = 5
    Adult
    Senior
End Enum

In this case, Teen now would now have a value of 5, Adult would have a value of 6, and Senior would have a value of 7. You can also assign a value to more than one member of an enumeration. Here is an example:

Enum MembershipType
    Teen = 3
    Adult = 8
    Senior
End Enum

In this case, Senior would have a value of 9.

An enumeration is very useful in a Select Case statement where it can be used in case sections. An advantage of using an enumerator is its ability to be more explicit than a regular integer. To use an enumeration, define it and list each one of its members for the case that applies. Here is an example of a Select Case statement that uses an enumeration.

Imports System

Module Module1
    Enum EmploymentStatus
        FullTime
        PartTime
        Contractor
        NotSpecified
    End Enum

    Sub Main()
        Dim EmplStatus As Integer

        Console.WriteLine("Employee's Contract Status: ")
        Console.WriteLine("0 - Full Time | 1 - Part Time")
        Console.WriteLine("2 - Contractor | 3 - Other")
        Console.Write("Status: ")
        Dim Status As String = Console.ReadLine()
        EmplStatus = Integer.Parse(Status)

        Console.WriteLine()

        Select Case EmplStatus
            Case EmploymentStatus.FullTime
                Console.WriteLine("Employment Status: Full Time")
                Console.WriteLine("Employee's Benefits: Medical Insurance")
                Console.WriteLine(" Sick Leave")
                Console.WriteLine(" Maternal Leave")
                Console.WriteLine(" Vacation Time")
                Console.WriteLine(" 401K")

            Case EmploymentStatus.PartTime
                Console.WriteLine("Employment Status: Part Time")
                Console.WriteLine("Employee's Benefits: Sick Leave")
                Console.WriteLine(" Maternal Leave")

            Case EmploymentStatus.Contractor
                Console.WriteLine("Employment Status: Contractor")
                Console.WriteLine("Employee's Benefits: None")

            Case EmploymentStatus.NotSpecified
                Console.WriteLine("Employment Status: Other")
                Console.WriteLine("Status Not Specified")

            Case Else
                Console.WriteLine("Unknown Status\n")
        End Select
    End Sub

End Module

Here is an example of running the program:

Employee's Contract Status:
0 - Full Time | 1 - Part Time
2 - Contractor | 3 - Other
Status: 0

Employment Status: Full Time
Employee's Benefits: Medical Insurance
 Sick Leave
 Maternal Leave
 Vacation Time
 401K
Press any key to continue
 

Practical Learning Practical Learning: Using an Enumerator

  1. To use an enumeration, in Notepad, change the contents of the file as follows:
     
    Imports System
    
    Module Module1
        Enum TypeOfApplication
    	NewDriversLicense = 1
    	UpgradeFromIDCard
    	TransferFromAnotherState
        End Enum
    
        Sub Main()
    	Dim FirstName As String, LastName As String
    	Dim OrganDonorAnswer As String
    	Dim Sex As Char, Gender As String
    	Dim DLClass As String
    	
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Application ---")
    	Console.WriteLine(" - Select the type of application -")
    	Console.WriteLine("1 - Applying for a brand new Driver's License")
    	Console.WriteLine("2 - Applicant already had an ID Card and is applying for a Driver's License")
    	Console.WriteLine("3 - Applicant is transferring his/her Driver's License from another state")
    	Console.Write("Your Choice: ")
    	Dim itype As Integer = CInt(Console.ReadLine())
    	Console.Write("First Name: ")
    	FirstName = Console.ReadLine()
    	Console.Write("Last Name:  ")
    	LastName = Console.ReadLine()
    	Console.Write("Sex(F=Female/M=Male): ")
    	Sex = char.Parse(Console.ReadLine())
    	Console.WriteLine(" - Driver's License Class -")
    	Console.WriteLine("A - All Non-commercial vehicles except motorcycles")
    	Console.WriteLine("B - Non-commercial vehicles up to and including 26,001/more lbs.")
    	Console.WriteLine("C - Cars, pick-up trucks, non-commercial vehicles 26,000 lbs.")
    	Console.WriteLine("K - Mopeds")
    	Console.WriteLine("M - Motorcycles")
    	Console.Write("Your Choice: ")
    	DLClass = char.Parse(Console.ReadLine())
    	Console.Write("Are you willing to be an Organ Donor(1=Yes/0=No)? ")
    	OrganDonorAnswer = Console.ReadLine()
    
    	if Sex = "f" Then
    	    Gender = "Female"
    	ElseIf Sex = "F" Then
    	    Gender = "Female"
    	ElseIf Sex = "m" Then
    	    Gender = "Male"
    	ElseIf Sex = "M" Then
    	    Gender = "Male"
    	else
    	    Gender = "Unknown"
    	End If
    
    	Console.WriteLine()
    	Console.WriteLine(" -=- Motor Vehicle Administration -=-")
    	Console.WriteLine(" --- Driver's License Information ---")
    
    	Console.Write("Type of Application: ")
    	Select Case iType
    	    case TypeOfApplication.NewDriversLicense
    		Console.WriteLine("New Driver's License")
    
    	    case TypeOfApplication.UpgradeFromIDCard
    		Console.WriteLine("Upgrade From Identity Card")
    
    	    case TypeOfApplication.TransferFromAnotherState
    		Console.WriteLine("Transfer From Another State")
    	
    	    Case Else
    		Console.WriteLine("Not Specified")
    	End Select
    
    	Console.WriteLine("Full Name: {0} {1}", FirstName, LastName)
    	Console.WriteLine("Sex:         {0}", Gender)
    
    	Select Case DLClass
    	case "a", "A"
    	    Console.WriteLine("Class:       A")
    	case "b", "B"
    	    Console.WriteLine("Class:       B")
    	case "c", "C"
    	    Console.WriteLine("Class:       C")
    	case "k", "K"
    	    Console.WriteLine("Class:       K")
    	case "m", "M"
    	    Console.WriteLine("Class:       M")
    	Case Else
    	    Console.WriteLine("Class:       Unknown")
    	End Select
    
    	Console.Write("Organ Donor? ")
    	if OrganDonorAnswer = "1" Then
    	    Console.WriteLine("Yes")
            ElseIf OrganDonorAnswer = "0" Then
    	    Console.WriteLine("No")
    	Else
    	    Console.WriteLine("N/A")
    	End If
    
    	Console.WriteLine()
        End Sub
    
    End Module
  2. Save the file and switch to the Command Prompt
  3. Compile and execute it 
  4. Return to Notepad
 

Previous Copyright © 2004-2015 FunctionX, Inc. Next