Introduction to Conditional Statements

Checking Whether a Condition is True/False

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, the Visual Basic language 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 Microsoft Visual Basic and create a Console Application named BCR1
  2. In the Solution Explorer, right-click Module1.vb and click Rename
  3. Type BethesdaCarRental.vb and press Enter
  4. Accept to change the file name and change the document as follows:
     
    Module BethesdaCarRental
    
        Public Function Main() As Integer
            Dim EmployeeName As String
            Dim StrHourlySalary As String, StrWeeklyHours As String
            Dim HourlySalaryFormatter As String
            Dim WeeklyHoursFormatter As String
            Dim Payroll As String
    
            HourlySalaryFormatter = "0.00"
            WeeklyHoursFormatter = "0.00"
    
    console.write("Enter Employee Name: ")
            EmployeeName = console.readline
            console.write("Enter Employee Hourly Salary: ")
            StrHourlySalary = console.readline
    
            HourlySalaryFormatter = FormatCurrency(CDbl(StrHourlySalary))
    
    console.write("Enter Employee Weekly Hours: ")
            StrWeeklyHours = console.readline
    
            WeeklyHoursFormatter = FormatNumber(CDbl(StrWeeklyHours))
    
            console.writeline ( "======================" )
     console.writeline (                 "=//= BETHESDA CAR RENTAL =//=" )
       console.writeline (               "==-=-= Employee Payroll =-=-==" )
       console.writeline (               "-------------------------------------------" )
       console.writeline (               "Employee Name: " & vbTab & EmployeeName   )
       console.writeline (               "Hourly Salary: " & vbTab &
       console.writeline (               HourlySalaryFormatter )
       console.writeline (               "Weekly Hours: " & vbTab &
         console.writeline (             WeeklyHoursFormatter )
            console.writeline (          "======================"                           )
            Return 0
        End Function
    
    End Module
  5. To execute the exercise, press Ctrl + F5
  6. Enter the Employee name as Helene Mukoko, the hourly salary as 22.35, and the weekly hours as 38
     
    Payroll
    Payroll
    Payroll
    Payroll
  7. Close the message box and the DOS window to return to your programming environment

If a Condition is True/False, Then What?

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:

Module Exercise

    Public Function Main() As Integer
        Dim IsMarried As Boolean
        Dim TaxRate As Double

        TaxRate = 33.0

        console.writeline (               "Tax Rate: " & TaxRate & "%")

        IsMarried = True

        If IsMarried = True Then TaxRate = 30.65

console.writeline (                       "Tax Rate: " & TaxRate & "%")
        Return 0
    End Function

End Module

This would produce:

If Condition If Condition

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:

Module Exercise

    Public Function Main() As Integer
        Dim IsMarried As Boolean
        Dim TaxRate As Double

        TaxRate = 33.0

        MsgBox("Tax Rate: " & TaxRate & "%")

        IsMarried = True
        If IsMarried = True Then
            TaxRate = 30.65

            console.writeline (               "Tax Rate: " & TaxRate & "%")
        End If

        Return 0
    End Function

End Module

Practical LearningPractical Learning: Using If...Then

  1. To use an If condition, change the document as follows:
    Module BethesdaCarRental
    
        Public Function Main() As Integer
            Dim EmployeeName As String
            Dim StrHourlySalary As String, StrWeeklyHours As String
            Dim HourlySalaryFormatter As String
            Dim WeeklyHoursFormatter As String
            Dim Payroll As String
    
            HourlySalaryFormatter = "0.00"
            WeeklyHoursFormatter = "0.00"
    
            EmployeeName = console.write("Enter Employee Name: ",
                                    "Bethesda Car Rental", "John Doe")
            StrHourlySalary = console.write("Enter Employee Hourly Salary: ",
                                    "Bethesda Car Rental", "0.00")
    
            If IsNumeric(StrHourlySalary) = True Then
                HourlySalaryFormatter = FormatCurrency(CDbl(StrHourlySalary))
            End If
    
            StrWeeklyHours = console.write("Enter Employee Weekly Hours: ",
                                    "Bethesda Car Rental", "0.00")
    
            If IsNumeric(StrWeeklyHours) = True Then
                WeeklyHoursFormatter = FormatNumber(CDbl(StrWeeklyHours))
            End If
    
            console.writeline (                 "======================" )
     console.writeline (                                "=//= BETHESDA CAR RENTAL =//=" )
     console.writeline (                                "==-=-= Employee Payroll =-=-==" )
      console.writeline (                               "-------------------------------------------" )
       console.writeline (                              "Employee Name: " & vbTab & EmployeeName )
      console.writeline (                               "Hourly Salary: " & vbTab &
      console.writeline (                               HourlySalaryFormatter )
       console.writeline (                              "Weekly Hours: " & vbTab &
         console.writeline (                            WeeklyHoursFormatter )
           console.writeline (                          "======================"
    
        End Function
    
    End Module
  2. Execute the application
  3. Enter the Employee name as Helene Mukoko, the hourly salary as 2W.o5, and the weekly hours as Thirty Eight
     
    Payroll
  4. Close the message box and the DOS window then return to your programming environment

Using the Default Value of a Boolean Expression

In the previous lesson, we saw that when you declare a Boolean variable, by default, it is initialized with the False value. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim IsMarried As Boolean

        MsgBox("Employee Is Married? " & IsMarried)
        
        Return 0
    End Function

End Module

This would produce:

Boolean Variable

Based on this, if you want to check whether a newly declared and uninitialized Boolean variable is false, you can omit the = False expression applied to it. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim IsMarried As Boolean
        Dim TaxRate As Double

        TaxRate = 33.0

        If IsMarried Then TaxRate = 30.65

        MsgBox("Tax Rate: " & TaxRate & "%")

        Return 0
    End Function

End Module

This would produce:

Boolean Variable

Notice that there is no = after the If IsMarried expression. In this case, the compiler assumes that the value of the variable is False. On the other hand, if you want to check whether the variable is True, make sure you include the = True expression. Overall, whenever in doubt, it is safer to always initialize your variable and it is safer to include the = True or = False expression when evaluating the variable:

Module Exercise

    Public Function Main() As Integer
        Dim IsMarried As Boolean
        Dim TaxRate As Double

        TaxRate = 36.45 ' %

        IsMarried = True

        If IsMarried = False Then TaxRate = 33.15

        MsgBox("Tax Rate: " & TaxRate & "%")

        Return 0
    End Function

End Module

In the previous lesson, we introduced some Boolean-based functions such IsNumeric and IsDate. The default value of these functions is true. This means that when you call them, you can omit the = True expression.

Practical LearningPractical Learning: Using the Default Value of Boolean-Based Functions

  1. To use the default value of the IsNumeric function, change the document as follows:
    Module BethesdaCarRental
    
        Public Function Main() As Integer
            . . . No Change
    
            If IsNumeric(StrHourlySalary) Then
                HourlySalaryFormatter = FormatCurrency(CDbl(StrHourlySalary))
            End If
    
            . . . No Change
    
            If IsNumeric(StrWeeklyHours) Then
                WeeklyHoursFormatter = FormatNumber(CDbl(StrWeeklyHours))
            End If
    
            . . . No Change
            Return 0
        End Function
    
    End Module
  2. Save the file

If-Condition Based Functions

 

Choosing a Value

We have learned how to check whether a condition is True or False and take an action. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim Status As UShort, EmploymentStatus As String

        Status = 1
        EmploymentStatus = "Unknown"

        If Status = 1 Then
            EmploymentStatus = "Full Time"
        End If

        MsgBox("Employment Status: " & EmploymentStatus)

        Return 0
    End Function

End Module

To provide an alternative to this operation, the Visual Basic language provides a function named Choose. Its syntax is:

Public Function Choose( _
   ByVal Index As Double, _ 
   ByVal ParamArray Choice() As Object _
) As Object

This function takes two required arguments. The fist argument is equivalent to the ConditionToCheck of our If...Then formula. For the Choose() function, this first argument must be a number (a Byte, an SByte, a Short, a UShort, an Integer, a UInteger, a Long, a ULong, a Single, a Double, or a Decimal value). This is the value against which the second argument will be compared. Before calling the function, you must know the value of the first argument. To take care of this, you can first declare a variable and initialize it with the desired value. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim Status As UShort

        Status = 1

        Choose(Status, ...)

        Return 0
    End Function

End Module

The second argument can be the Statement of our formula. Here is an example:

Choose(Status, "Full Time")

We will see in the next sections that the second argument is actually a list of values and each value has a specific position referred to as its index. To use the function in an If...Then scenario, you pass only one value as the second argument. This value/argument has an index of 1. When the Choose() function is called in an If...Then implementation, if the first argument holds a value of 1, the second argument is validated.

When the Choose() function has been called, it returns a value of type Object. You can retrieve that value, store it in a variable and use it as you see fit. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim Status As UShort, EmploymentStatus As String

        Status = 1

        EmploymentStatus = Choose(Status, "Full Time")

        MsgBox("Employment Status: " & EmploymentStatus)

        Return 0
    End Function

End Module

This would produce:

Choose

Switching to a Value

To give you another alternative to an If...Then condition, the Visual Basic language provides a function named Switch. Its syntax is:

Public Function Switch( _
    ByVal ParamArray VarExpr() As Object _
) As Object
In the .NET Framework, there is another Switch implement that can cause a conflict when you call the Switch() function in your program. Therefore, you must qualify this function when calling it. To do this, use Microsoft.VisualBasic.Switch.

This function takes one required argument. To use it in an If...Then scenario, pass the argument as follows:

Switch(ConditionToCheck, Statement)

In the ConditionToCheck placeholder, pass a Boolean expression that can be evaluated to True or False. If that condition is true, the second argument would be executed.

When the Switch() function has been called, it produces a value of type Object (such as a string) that you can use as you see fit. For example, you can store it in a variable. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim Status As UShort, EmploymentStatus As String

        Status = 2
        EmploymentStatus = "Unknown"

        EmploymentStatus =
		Microsoft.VisualBasic.Switch(Status = 1, "Full Time")

        console.writeline (               "Employment Status: " & EmploymentStatus)

        Return 0
    End Function

End Module

In this example, we used a number as argument. You can also use another type of value, such as an enumeration. Here is an example:

Module Exercise
    Private Enum EmploymentStatus
        FullTime
        PartTime
        Contractor
        Seasonal
        Unknown
    End Enum

    Public Function Main() As Integer
        Dim Status As EmploymentStatus
        Dim Result As String

        Status = EmploymentStatus.FullTime
        Result = "Unknown"

        Result = Microsoft.VisualBasic.Switch( _
			Status = EmploymentStatus.FullTime, "Full Time")

        console.writeline (               "Employment Status: " & Result)

        Return 0
    End Function

End Module

What Else When a Condition is True/False?  

The If...Then...Else Condition

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:

Module Exercise

    Public Function Main() As Integer
        Dim MemberAge As Int16
        Dim MemberCategory As String

        MemberAge = 16

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

        console.writeline (               "Membership: " & MemberCategory)

        Return 0
    End Function

End Module

This would produce:

If...Then...Else

 

Practical LearningPractical Learning: Using If...Then...Else

  1. To use the Else clause, make the following changes to the file:
    Module BethesdaCarRental
    
        Public Function Main() As Integer
            Dim EmployeeName As String
            Dim StrHourlySalary As String, StrWeeklyHours As String
            Dim HourlySalaryFormatter As String
            Dim WeeklyHoursFormatter As String
            Dim Payroll As String
    
            HourlySalaryFormatter = "0.00"
            WeeklyHoursFormatter = "0.00"
    
            EmployeeName = console.write("Enter Employee Name: ",
                                    "Bethesda Car Rental", "John Doe")
            StrHourlySalary = console.write("Enter Employee Hourly Salary: ",
                                    "Bethesda Car Rental", "0.00")
    
            If IsNumeric(StrHourlySalary) Then
                HourlySalaryFormatter = FormatCurrency(CDbl(StrHourlySalary))
            Else
                console.writeline (               "The number " & StrHourlySalary & " you entered " &
                       "for the hourly salary is not valid"                                          )
            End If
    
            StrWeeklyHours = console.write("Enter Employee Weekly Hours: ",
                                    "Bethesda Car Rental", "0.00")
    
            If IsNumeric(StrWeeklyHours) Then
                WeeklyHoursFormatter = FormatNumber(CDbl(StrWeeklyHours))
            Else
                console.writeline (               "The value " & StrWeeklyHours & " you provided " &
                       "for the weekly hours is not valid")
            End If
    
            console.writeline (                 "======================" )
     console.writeline (                                "=//= BETHESDA CAR RENTAL =//=" )
     console.writeline (                                "==-=-= Employee Payroll =-=-==" )
     console.writeline (                                "-------------------------------------------" )
     console.writeline (                                "Employee Name: " & vbTab & EmployeeName )
     console.writeline (                                "Hourly Salary: "   )
     console.writeline (                                HourlySalaryFormatter )
    console.writeline (                                 "Weekly Hours: "   )
     console.writeline (                                WeeklyHoursFormatter )
      console.writeline (                               "======================")
            Return 0
        End Function
    
    End Module
  2. Execute the application
  3. Enter the Employee name as Helene Mukoko, the hourly salary as 2W.o5, and the weekly hours as Thirty Eight
  4. Close the message box and the DOS window then return to your programming environment
  5. To calculate the employee's pay, change the document as follows:
    Module BethesdaCarRental
    
        Public Function Main() As Integer
            Dim EmployeeName As String
            Dim StrHourlySalary As String, StrWeeklyHours As String
            Dim HourlySalary As Double
            Dim WeeklyHours As Double
            Dim RegularTime As Double, Overtime As Double
            Dim RegularPay As Double, OvertimePay As Double
            Dim NetPay As Double
    
            Dim Payroll As String
    
            HourlySalary = "0.00"
            WeeklyHours = "0.00"
    
    console.write("Enter Employee Name: "                                    )
            EmployeeName = console.readline
            
            console.write("Enter Employee Hourly Salary: "                                   )
            StrHourlySalary = console.readline
    
            If IsNumeric(StrHourlySalary) Then
                HourlySalary = CDbl(StrHourlySalary)
            Else
                console.writeline (               "The number " & StrHourlySalary & " you entered " &
                       "for the hourly salary is not valid"                                          )
            End If
    
    console.write("Enter Employee Weekly Hours: "                                   )
            StrWeeklyHours = console.readline
    
            If IsNumeric(StrWeeklyHours) Then
                WeeklyHours = CDbl(StrWeeklyHours)
            Else
                console.writeline("The value " & StrWeeklyHours & " you provided " &
                       "for the weekly hours is not valid"                                          )
            End If
    
            If WeeklyHours < 40 Then
                RegularTime = WeeklyHours
                Overtime = 0
                RegularPay = HourlySalary * RegularTime
                OvertimePay = 0
                NetPay = RegularPay
            Else
                RegularTime = 40
                Overtime = WeeklyHours - 40
                RegularPay = HourlySalary * 40
                OvertimePay = HourlySalary * Overtime
                NetPay = RegularPay + OvertimePay
            End If
    
            console.writeline ( "======================" )
    console.writeline (                  "=//= BETHESDA CAR RENTAL =//=" )
    console.writeline (                  "==-=-= Employee Payroll =-=-==" )
    console.writeline (                  "-------------------------------------------" )
     console.writeline (                 "Employee Name: " & vbTab & EmployeeName )
     console.writeline (                 "Hourly Salary: " & vbTab &                   FormatCurrency(HourlySalary) )
     console.writeline (                 "Weekly Hours: " & vbTab &                   FormatNumber(WeeklyHours) )
     console.writeline (                 "Regular Pay: " & vbTab &  			FormatCurrency(RegularPay) )
    console.writeline (                  "Overtime Pay: " & vbTab & 			FormatCurrency(OvertimePay) )
    console.writeline (                  "Total Pay: " & vbTab & FormatCurrency(NetPay) )
                      "======================")
            Return 0
        End Function
    
    End Module
  6. Execute the application
  7. Enter the Employee name as Helene Mukoko, the hourly salary as 22.35, and the weekly hours as 42.50
     
    Payroll
  8. Close the message box and the DOS window then return to your programming environment
 

If...Then...Else-Condition Based Functions

 

Immediate If

To assist you with checking a condition and its alternative, the Visual Basic language provides a function named IIf. Its syntax is:

Public Function IIf( _
   ByVal Expression As Boolean, _ 
   ByVal TruePart As Object, _ 
   ByVal FalsePart As Object _ 
) As Object

This function operates like an If...Then...Else condition. It takes three required arguments and returns a result of type Object. This returned value will hold the result of the function.

The condition to check is passed as the first argument:

  • If that condition is true, the function returns the value of the TruePart argument and the last argument is ignored
  • If the condition is false, the first argument is ignored and the function returns the value of the second argument

As mentioned already, you can retrieved the value of the right argument and assign it to the result of the function. The expression we saw early can be written as follows:

Module Exercise

    Public Function Main() As Integer
        Dim MemberAge As Int16
        Dim MemberCategory As String

        MemberAge = 16

        MemberCategory = IIf(MemberAge <= 18, "Teen", "Adult")

        MsgBox("Membership: " & MemberCategory)

        Return 0
    End Function

End Module

This would produce the same result we saw earlier.

Practical LearningPractical Learning: Using the Immediate If Function

  1. To use the IIf() function, change the document as follows:
    Module BethesdaCarRental
    
        Public Function Main() As Integer
            Dim EmployeeName As String
            Dim Gender As Byte
            Dim StrGender As String
            Dim StrHourlySalary As String, StrWeeklyHours As String
            Dim HourlySalary As Double
            Dim WeeklyHours As Double
            Dim RegularTime As Double, Overtime As Double
            Dim RegularPay As Double, OvertimePay As Double
            Dim NetPay As Double
    
            Dim Payroll As String
    
            HourlySalary = "0.00"
            WeeklyHours = "0.00"
    
    console.write("Enter Employee Name: ",                                                                     )
            EmployeeName = console.readline
    
            Gender = console.write("Enter Employee Gender (1=Female/2=Male): ",
                                    "Bethesda Car Rental", "1")
            StrGender = IIf(Gender = 1, "Female", "Male")
    
            StrHourlySalary = console.write("Enter Employee Hourly Salary: ",
                                    "Bethesda Car Rental", "0.00")
    
            If IsNumeric(StrHourlySalary) Then
                HourlySalary = CDbl(StrHourlySalary)
            Else
                console.writeline("The number " & StrHourlySalary & " you entered " &
                       "for the hourly salary is not valid"                                          )
            End If
    
    console.write("Enter Employee Weekly Hours: "                                   )
            StrWeeklyHours = console.readline
    
            If IsNumeric(StrWeeklyHours) Then
                WeeklyHours = CDbl(StrWeeklyHours)
            Else
                console.writeline("The value " & StrWeeklyHours & " you provided " &
                       "for the weekly hours is not valid"                                          )
            End If
    
            If WeeklyHours < 40 Then
                RegularTime = WeeklyHours
                Overtime = 0
                RegularPay = HourlySalary * RegularTime
                OvertimePay = 0
                NetPay = RegularPay
            Else
                RegularTime = 40
                Overtime = WeeklyHours - 40
                RegularPay = HourlySalary * 40
                OvertimePay = HourlySalary * Overtime
                NetPay = RegularPay + OvertimePay
            End If
    
            console.writeline(  "======================" )
    console.writeline(                  "=//= BETHESDA CAR RENTAL =//=" )
                      console.writeline("==-=-= Employee Payroll =-=-==" )
     console.writeline(                 "-------------------------------------------" )
     console.writeline(                 "Employee Name: " & vbTab & EmployeeName )
     console.writeline(                 "Employee Gender: " & vbTab & StrGender )
     console.writeline(                 "Hourly Salary: " & vbTab &                  FormatCurrency(HourlySalary) )
     console.writeline(                 "Weekly Hours: " & vbTab &                  FormatNumber(WeeklyHours) )
       console.writeline(          "Regular Pay: " & vbTab & FormatCurrency(RegularPay) )
         console.writeline(        "Overtime Pay: " & vbTab & FormatCurrency(OvertimePay) )
        console.writeline(              "Total Pay: " & vbTab & FormatCurrency(NetPay) )
        console.writeline(              "======================")
            Return 0
        End Function
    
    End Module
  2. Execute the application
  3. Enter the Employee name as Raymond Kouma, the gender as 2, hourly salary as 28.25, and the weekly hours as 44.50
     
    Payroll
  4. Close the message box and the DOS window then return to your programming environment
  5. Create a new Console Application named BCR2
  6. In the Solution Explorer, right-click Module1.vb and click Rename
  7. Type BethesdaCarRental.vb and press Enter
  8. Accept to change the file name and change the document as follows:
    Module BethesdaCarRental
    
        Public Function Main() As Integer
            Dim CustomerName As String
            Dim RentStartDate As Date, RentEndDate As Date
            Dim NumberOfDays As Integer
            Dim RateType As String, RateApplied As Double
            Dim OrderTotal As Double
            Dim OrderInvoice As String
    
            RateType = "Weekly Rate"
            RateApplied = 0
            OrderTotal = RateApplied
    
            CustomerName = console.write("Enter Customer Name: ", _
                                           "Bethesda Car Rental", "John Doe")
    
            RentStartDate = CDate(console.write("Enter Rent Start Date: ", _
                                           "Bethesda Car Rental", #1/1/1900#))
            RentEndDate = CDate(console.write("Enter Rend End Date: ", _
                                           "Bethesda Car Rental", #1/1/1900#))
            NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)
    
            RateApplied = CDbl(console.write("Enter Rate Applied: ",
                                           "Bethesda Car Rental", 0))
    
            console.writeline(  "===========================" )
     console.writeline(                 "=//= BETHESDA CAR RENTAL =//=" )
     console.writeline(                "==-=-= Order Processing =-=-==" )
     console.writeline(             "------------------------------------------------" )
      console.writeline(                "Processed for: " & vbTab & CustomerName )
      console.writeline(            "------------------------------------------------" )
      console.writeline(                "Start Date: " & vbTab & RentStartDate )
      console.writeline(                "End Date: " & vbTab & RentEndDate )
      console.writeline(                "Nbr of Days: " & vbTab & NumberOfDays )
      console.writeline(            "------------------------------------------------" )
       console.writeline(           "Rate Type: " & vbTab & RateType )
      console.writeline(                "Rate Applied: " & vbTab & RateApplied )
      console.writeline(            "Order Total: " & vbTab & FormatCurrency(OrderTotal) )
       console.writeline(               "==========================="                                             )
            Return 0
        End Function
    
    End Module
  9. Execute the application
  10. Enter the customer name as James Wiley, the start date as 11/07/2008, the end date as 11/10/2008, and the rate applied 49.95
     
    Bethesda Car Rental
    Bethesda Car Rental
    Bethesda Car Rental
    Bethesda Car Rental
    Bethesda Car Rental
  11. Close the message box and the DOS window to return to your programming environment

Choose an Alternate Value

We saw how to call a function named Choose where only one value is being considered. The reality is that if there is an alternate value, the function produces a null result. Consider the same program we used earlier but with a different value:

Module Exercise

    Public Function Main() As Integer
        Dim Status As UShort, EmploymentStatus As String

        Status = 2

        EmploymentStatus = Choose(Status, "Full Time")

        MsgBox(EmploymentStatus)

        Return 0
    End Function

End Module

This would produce:

Choose

 

Notice that the function returns nothing (an empty string). To use this function as an alternative to the If...Then...Else operation, you can pass two values for the second argument. The second argument is actually passed as a list of values. Each value has a specific position as its index. To use the function in an If...Then...Else implementation, pass two values for the second argument. Here is an example:

Choose(Status, "Full Time", "Part Time")

The second argument to the function, which is the first value of the Choose argument, has an index of 1. The third argument to the function, which is the second value of the Choose argument, has an index of 2. 

When the Choose() function is called, if the first argument has a value of 1, then the second argument is validated. If the first argument has a value of 2, then the third argument is validated. As mentioned already, you can retrieve the returned value of the function and use it however you want. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim Status As UShort, EmploymentStatus As String

        Status = 2

        EmploymentStatus = Choose(Status, "Full Time", "Part Time")

        MsgBox("Employment Status: " & EmploymentStatus)

        Return 0
    End Function

End Module

This would produce:

Choose

Switching to an Alternate Value

We saw earlier how to call the Switch function in an If...Then condition. Once again, the problem is that if you call it with a value that is not checked by the first argument, the function produces a null value (an empty string). To apply this function to an If...Then...Else scenario, you can call it using the following formula:

Switch(Condition1ToCheck, Statement1, Condition2ToCheck, Statement2)

In the Condition1ToCheck placeholder, pass a Boolean expression that can be evaluated to True or False. If that condition is true, the second argument would be executed. To provide an alternative to the first condition, pass another condition as Condition2ToCheck. If the Condition2ToCheck is true, then Statement2 would be executed. Once gain, remember that you can get the value returned by the Switch function and use it. Here is an example:

Module Exercise
    Private Enum EmploymentStatus
        FullTime
        PartTime
        Contractor
        Seasonal
        Unknown
    End Enum

    Public Function Main() As Integer
        Dim Status As EmploymentStatus
        Dim Result As String

        Status = EmploymentStatus.PartTime
        Result = "Unknown"

        Result = Microsoft.VisualBasic.Switch( _
                    Status = EmploymentStatus.FullTime, "Full Time",
                    Status = EmploymentStatus.PartTime, "Part Time")

        MsgBox("Employment Status: " & Result)

        Return 0
    End Function

End Module

This would produce:

Choose

Alternatives to a Condition Being True/False?

 

The If...Then...ElseIf Condition

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 that is true. 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:

Module Exercise

    Public Function Main() As Integer
        Dim MemberAge As Short

        MemberAge = 32

        If MemberAge <= 18 Then
            MsgBox("Membership: " & "Teen")
        ElseIf MemberAge < 55 Then
            MsgBox("Membership: " & "Adult")
        End If

        Return 0
    End Function

End Module

This would produce:

If Condition

What If No Alternative is Valid?

There is still a possibility that none of the stated conditions be 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:

Module Exercise

    Public Function Main() As Integer
        Dim MemberAge As Short

        MemberAge = 65

        If MemberAge <= 18 Then
            MsgBox("Membership: " & "Teen")
        ElseIf MemberAge < 55 Then
            MsgBox("Membership: " & "Adult")
        Else
            MsgBox("Membership: " & "Senior")
        End If

        Return 0
    End Function

End Module

This would produce:

Else

Practical LearningPractical Learning: Using If...Then...ElseIf

  1. Start Microsoft Visual Basic and create a Console Application named BCR3
  2. In the Solution Explorer, right-click Module1.vb and click Rename
  3. Type BethesdaCarRental.vb and press Enter
  4. Accept to change the file name
  5. To use an If...Then...ElseIf condition, change the document as follows:
     
    Module BethesdaCarRental
    
        Public Function Main() As Integer
            Dim EmployeeNumber As Long, EmployeeName As String
            Dim CustomerName As String
            Dim RentStartDate As Date, RentEndDate As Date
            Dim NumberOfDays As Integer
            Dim RateType As String, RateApplied As Double
            Dim OrderTotal As Double
            Dim OrderInvoice As String
    
            RateType = "Weekly Rate"
            RateApplied = 0
            OrderTotal = RateApplied
    
            EmployeeNumber = _
    		CLng(console.write("Employee number (who processed this order): ",
                                           "Bethesda Car Rental", "00000"))
    
            If EmployeeNumber = 22804 Then
                EmployeeName = "Helene Mukoko"
            ElseIf EmployeeNumber = 92746 Then
                EmployeeName = "Raymond Kouma"
            ElseIf EmployeeNumber = 54080 Then
                EmployeeName = "Henry Larson"
            ElseIf EmployeeNumber = 86285 Then
                EmployeeName = "Gertrude Monay"
            Else
                EmployeeName = "Unknown"
            End If
    
            CustomerName = console.write("Enter Customer Name: ", _
                                           "Bethesda Car Rental", "John Doe")
    
            RentStartDate = CDate(console.write("Enter Rent Start Date: ", _
                                           "Bethesda Car Rental", #1/1/1900#))
            RentEndDate = CDate(console.write("Enter Rend End Date: ", _
                                           "Bethesda Car Rental", #1/1/1900#))
            NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)
    
            RateApplied = CDbl(console.write("Enter Rate Applied: ", _
                                           "Bethesda Car Rental", 0))
    
            OrderInvoice = "===========================" )
                      "=//= BETHESDA CAR RENTAL =//=" )
                      "==-=-= Order Processing =-=-==" )
                  "------------------------------------------------" )
                      "Processed by: " & vbTab & EmployeeName )
                      "Processed for: " & vbTab & CustomerName )
                  "------------------------------------------------" )
                      "Start Date: " & vbTab & RentStartDate )
                      "End Date: " & vbTab & RentEndDate )
                      "Nbr of Days: " & vbTab & NumberOfDays )
                  "------------------------------------------------" )
                      "Rate Type: " & vbTab & RateType )
                      "Rate Applied: " & vbTab & RateApplied )
                  "Order Total: " & vbTab & FormatCurrency(OrderTotal) )
                      "==========================="
    
            MsgBox(OrderInvoice,
                      MsgBoxStyle.Information Or MsgBoxStyle.OkOnly,
                   "Bethesda Car Rental")
            Return 0
        End Function
    
    End Module
  6. Execute the application
  7. Enter the employee number as 54080, the customer name as James Wiley, the start date as 11/05/2008, the end date as 11/15/2008, and the rate applied 49.95
     
    Car Rental
  8. Close the message box and the DOS window to return to your programming environment

Conditional Statements and Functions

 

Introduction

As introduced in Lesson 5 and as seen in lessons thereafter, we know that a function is used to perform a specific assignment and produce a result. Here is an example:

Private Function SetMembershipLevel$()
    Dim MemberAge%
    
console.write("Enter the Member's Age")
    MemberAge% = console.readline

    Return ""
End Function

When performing its assignment, a function can encounter different situations, some of which would need to be checked for truthfulness or negation. This means that conditional statements can assist a procedure with its assignment.

  1. Enter the customer name as Judith Nkolo, the rent start date as 11/05/2008, the rent end date as 11/15/2008, and the rate applied 39.95
     
    Bethesda Car Rental
  2. Close the message box and the DOS window to return to your programming environment

Conditional Returns

A function is meant to return a value. Sometimes, it will perform some tasks whose results would lead to different results. A function can return only one value (we saw that, by passing arguments by reference, you can make a procedure return more than one value) but you can make it render a result depending on a particular behavior. If a function is requesting an answer from the user, since the user can provide different answers, you can treat each result differently. Consider the following function:

Module Exercise

    Private Function SetMembershipLevel$()
        Dim MemberAge%

        MemberAge% = console.write("Enter the Member's Age")

        If MemberAge% < 18 Then
            Return "Teen"
        ElseIf MemberAge% < 55 Then
            Return "Adult"
        End If
    End Function

    Public Function Main() As Integer
        Dim Membership$

        MsgBox("Membership: " & Membership$)
        Return 0
    End Function

End Module

At first glance, this function looks fine. The user is asked to provide a number. If the user enters a number less than 18 (excluded), the function returns Teen. Here is an example of running the program:

Conditional Statements and Functions

Conditional Statements and Functions

If the user provides a number between 18 (included) and 55, the function returns the Adult. Here is another example of running the program:

Conditional Statements and Functions

Conditional Statements and Functions

What if there is an answer that does not fit those we are expecting? The values that we have returned in the function conform only to the conditional statements and not to the function. Remember that in If Condidion Statement, the Statement executes only if the Condition is true. Here is what will happen. If the user enters a number higher than 55 (excluded), the function will not execute any of the returned statements. This means that the execution will reach the End Function line without encountering a return value. This also indicates to the compiler that you wrote a function that is supposed to return a value, but by the end of the method, it didn't return a value. Here is another example of running the program:

Conditional Statements and Functions

Conditional Statements and Functions

The compiler would produce a warning:

Warning	1 Function 'SetMembershipLevel' doesn't return a value on all code paths.

To solve this problem, you have various alternatives. If the function uses an If...Then condition, you can create an Else section that embraces any value other than those validated previously. Here is an example:

Module Exercise

    Private Function SetMembershipLevel$()
        Dim MemberAge%

        MemberAge% = console.write("Enter the Member's Age")

        If MemberAge% < 18 Then
            Return "Teen"
        ElseIf MemberAge% < 55 Then
            Return "Adult"
        Else
            Return "Senior"
        End If

    End Function

    Public Function Main() As Integer
        Dim Membership$

        Membership$ = SetMembershipLevel$()
        MsgBox("Membership: " & Membership$)
        Return 0
    End Function

End Module

This time, the Else condition would execute if no value applies to the If or ElseIf conditions and the compiler would not produce a warning. Here is another example of running the program:

Conditional Statements and Functions

Conditional Statements and Functions

An alternative is to provide a last return value just before the End Function line. In this case, if the execution reaches the end of the function, it would still return something but you would know what it returns. This would be done as follows:

Private Function SetMembershipLevel$()
    Dim MemberAge%

    MemberAge% = console.write("Enter the Member's Age")

    If MemberAge% < 18 Then
        Return "Teen"
    ElseIf MemberAge% < 55 Then
        Return "Adult"
    End If

    Return "Senior"
End Function

If the function uses an If condition, both implementations would produce the same result.

Practical LearningPractical Learning: Using a Conditional Statement

  1. To use a conditional statement in a function, change the document as follows:
     
    Module BethesdaCarRental
        Private Function GetEmployeeName(ByVal EmplNbr As Long) As String
            Dim Name As String
    
            If EmplNbr = 22804 Then
                Name = "Helene Mukoko"
            ElseIf EmplNbr = 92746 Then
                Name = "Raymond Kouma"
            ElseIf EmplNbr = 54080 Then
                Name = "Henry Larson"
            ElseIf EmplNbr = 86285 Then
                Name = "Gertrude Monay"
            Else
                Name = "Unknown"
            End If
    
            Return Name
        End Function
    
        Public Function Main() As Integer
            Dim EmployeeNumber As Long, EmployeeName As String
            Dim CustomerName As String
            Dim RentStartDate As Date, RentEndDate As Date
            Dim NumberOfDays As Integer
            Dim RateType As String, RateApplied As Double
            Dim OrderTotal As Double
            Dim OrderInvoice As String
    
            RateType = "Weekly Rate"
            RateApplied = 0
            OrderTotal = RateApplied
    
            EmployeeNumber = CLng(console.write(
    		"Employee number (who processed this order): ",
                    "Bethesda Car Rental", "00000"))
    
            EmployeeName = GetEmployeeName(EmployeeNumber)
    
            CustomerName = console.write("Enter Customer Name: ", _
                                           "Bethesda Car Rental", "John Doe")
    
            RentStartDate = CDate(console.write("Enter Rent Start Date: ", _
                                           "Bethesda Car Rental", #1/1/1900#))
            RentEndDate = CDate(console.write("Enter Rend End Date: ", _
                                           "Bethesda Car Rental", #1/1/1900#))
            NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)
    
            RateApplied = CDbl(console.write("Enter Rate Applied: ", _
                                           "Bethesda Car Rental", 0))
    
            OrderInvoice = "===========================" )
                      "=//= BETHESDA CAR RENTAL =//=" )
                      "==-=-= Order Processing =-=-==" )
                      "------------------------------------------------" &
    		  vbCrLf & _
                      "Processed by: " & vbTab & EmployeeName )
                      "Processed for: " & vbTab & CustomerName )
                      "------------------------------------------------" &
    		  vbCrLf &
                      "Start Date: " & vbTab & RentStartDate )
                      "End Date: " & vbTab & RentEndDate )
                      "Nbr of Days: " & vbTab & NumberOfDays )
                      "------------------------------------------------" &
    		  vbCrLf &
                      "Rate Type: " & vbTab & RateType )
                      "Rate Applied: " & vbTab & RateApplied )
                      "Order Total: " & vbTab & FormatCurrency(OrderTotal) &
    		  vbCrLf &
                      "==========================="
    
            MsgBox(OrderInvoice,
                      MsgBoxStyle.Information Or MsgBoxStyle.OkOnly,
                   "Bethesda Car Rental")
            Return 0
        End Function
    
    End Module
  2. Execute the application
  3. Enter the employee number as 54080, the customer name as Sunil Ajat, the start date as 11/05/2008, the end date as 11/15/2008, and the rate applied 49.95
     
    Bethesda Car Rental
  4. Close the message box and the DOS window to return to your programming environment

If-Condition Built-In Functions

 

Using the Immediate If Function

The IIf() function can also be used in place of an If...Then...ElseIf scenario. When the function is called, the Expression is checked. As we saw already, if the expression is true, the function returns the value of the TruePart argument and ignores the last argument. To use this function as an alternative to If...Then...ElseIf statement, if the expression is false, instead of immediately returning the value of the FalsePart argument, you can translate that part into a new IIf function. The pseudo-syntax would become:

Public Function IIf( _
   ByVal Expression As Boolean, _ 
   ByVal TruePart As Object, _ 
   	Public Function IIf( _
   	    ByVal Expression As Boolean, _ 
   	    ByVal TruePart As Object, _ 
   	    ByVal FalsePart As Object _ 
	) As Object
) As Object

In this case, if the expression is false, the function returns the TruePart and stops. If the expression is false, the compiler accesses the internal IIf function and applies the same scenario. Here is example:

Module Exercise

    Public Function Main() As Integer
        Dim MemberAge As Short
        Dim MembershipCategory As String

        MemberAge = 74

        MembershipCategory = _
	    IIf(MemberAge <= 18, "Teen", IIf(MemberAge < 55, "Adult", "Senior"))

        MsgBox("Membership: " & MembershipCategory)
        Return 0
    End Function

End Module

We saw that in an If...Then...ElseIf statement you can add as many ElseIf conditions as you want. In the same, you can call as many IIf functions in the subsequent FalsePart sections as you judge necessary:

Public Function IIf(
   ByVal Expression As Boolean,
   ByVal TruePart As Object, 
   	Public Function IIf(
   	    ByVal Expression As Boolean,
   	    ByVal TruePart As Object,
   	    	Public Function IIf(
   	    	    ByVal Expression As Boolean,
   	    	    ByVal TruePart As Object, 
   	    		Public Function IIf(
   	    		    ByVal Expression As Boolean,
   	    		    ByVal TruePart As Object, 
   	    		    ByVal FalsePart As Object 
			) As Object
		) As Object
	) As Object
) As Object

Choose an Alternate Value

As we have seen so far, the Choose function takes a list of arguments. To use it as an alternative to the If...Then...ElseIf...ElseIf condition, you can pass as many values as you judge necessary for the second argument. The index of the first member of the second argument would be 1. The index of the second member of the second argument would be 2, and so on. When the function is called, it would first get the value of the first argument, then it would check the indexes of the available members of the second argument. The member whose index matches the first argument would be executed. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim Status As UShort, EmploymentStatus As String

        Status = 3

        EmploymentStatus = Choose(Status,
                                  "Full Time",
                                  "Part Time",
                                  "Contractor",
                                  "Seasonal")

        MsgBox("Employment Status: " & EmploymentStatus)

        Return 0
    End Function

End Module

This would produce:

Choose

 

So far, we have used only strings for the values of the second argument of the Choose() function. In reality, the values of the second argument can be almost anything. One value can be a constant. Another value can be a string. Yet another value can come from calling a function. Here is an example:

Module Exercise

    Private Function ShowContractors$()
        Return "=-= List of Contractors =-=" )
               "Martin Samson" )
               "Geneviève Lam" )
               "Frank Viel" )
               "Henry Rickson" )
               "Samuel Lott"
    End Function

    Public Function Main() As Integer
        Dim Status As UShort, Result$

        Status = 3

        Result = Choose(Status,
                        "Employment Status: Full Time",
                        "Employment Status: Part Time",
                        ShowContractors,
                        "Seasonal Employment")
        MsgBox(Result)

        Return 0
    End Function

End Module

This would produce:

The values of the second argument can even be of different types.

Practical LearningPractical Learning: Using the Choose Function

  1. To use the Choose() function, change the document as follows:
    Module BethesdaCarRental
        Private Function GetEmployeeName(ByVal EmplNbr As Long) As String
            Dim Name As String
    
            If EmplNbr = 22804 Then
                Name = "Helene Mukoko"
            ElseIf EmplNbr = 92746 Then
                Name = "Raymond Kouma"
            ElseIf EmplNbr = 54080 Then
                Name = "Henry Larson"
            ElseIf EmplNbr = 86285 Then
                Name = "Gertrude Monay"
            Else
                Name = "Unknown"
            End If
    
            Return Name
        End Function
    
        Public Function Main() As Integer
            Dim EmployeeNumber As Long, EmployeeName As String
            Dim CustomerName As String
            Dim Tank As Integer, TankLevel As String
            Dim RentStartDate As Date, RentEndDate As Date
            Dim NumberOfDays As Integer
            Dim RateType As String, RateApplied As Double
            Dim OrderTotal As Double
            Dim OrderInvoice As String
    
            RateType = "Weekly Rate"
            RateApplied = 0
            OrderTotal = RateApplied
    
            EmployeeNumber =
    	    CLng(console.write("Employee number (who processed this order): ",
                              "Bethesda Car Rental", "00000"))
    
            EmployeeName = GetEmployeeName(EmployeeNumber)
    
            CustomerName = console.write("Enter Customer Name: ",
                                           "Bethesda Car Rental", "John Doe")
            Tank = CInt(console.write("Enter Tank Level: " )
                                 "1. Empty" )
                                 "2. 1/4 Empty" )
                                 "3. 1/2 Full" )
                                 "4. 3/4 Full" )
                                 "5. Full",
                                 "Bethesda Car Rental", 1))
            TankLevel = Choose(Tank, "Empty", "1/4 Empty",
    			   "1/2 Full", "3/4 Full", "Full")
    
            RentStartDate = CDate(console.write("Enter Rent Start Date: ",
                                           "Bethesda Car Rental", #1/1/1900#))
            RentEndDate = CDate(console.write("Enter Rend End Date: ",
                                           "Bethesda Car Rental", #1/1/1900#))
            NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)
    
            RateApplied = CDbl(console.write("Enter Rate Applied: ", _
                                           "Bethesda Car Rental", 0))
    
            OrderInvoice = "===========================" )
                      "=//= BETHESDA CAR RENTAL =//=" )
                      "==-=-= Order Processing =-=-==" )
                  "------------------------------------------------" )
                      "Processed by: " & vbTab & EmployeeName )
                      "Processed for: " & vbTab & CustomerName )
                  "------------------------------------------------" )
                      "Car Selected: " )
                      vbTab & "Tank: " & vbTab & TankLevel )
                  "------------------------------------------------" )
                      "Start Date: " & vbTab & RentStartDate )
                      "End Date: " & vbTab & RentEndDate )
                      "Nbr of Days: " & vbTab & NumberOfDays )
                  "------------------------------------------------" )
                      "Rate Type: " & vbTab & RateType )
                      "Rate Applied: " & vbTab & RateApplied )
                  "Order Total: " & vbTab & FormatCurrency(OrderTotal) )
                      "==========================="
    
            MsgBox(OrderInvoice,
                      MsgBoxStyle.Information Or MsgBoxStyle.OkOnly,
                   "Bethesda Car Rental")
            Return 0
        End Function
    
    End Module
  2. Eexecute the application
  3. Enter the employee number as 22804, the customer name as George Livingstone, the tank level as 2, the start date as 09/15/2008, the end date as 09/19/2008, and the rate applied 65.75
     
    Car Rental
  4. Close the message box and the DOS window to return to your programming environment

Switching to an Alternate Value

The Switch() function is a prime alternative to the If...Then...ElseIf...ElseIf condition. The argument to this function is passed as a list of values. As seen previously, each value is passed as a combination of two values:

ConditionXToCheck, StatementX

As the function is accessed, the compiler checks each condition. If a condition X is true, its statement is executed. If a condition Y is false, the compiler skips it. You can provide as many of these combinations as you want. Here is an example:

Module Exercise
    Private Enum EmploymentStatus
        FullTime
        PartTime
        Contractor
        Seasonal
    End Enum

    Public Function Main() As Integer
        Dim Status As EmploymentStatus
        Dim Result As String

        Status = EmploymentStatus.Contractor
        Result = "Unknown"

        Result = Microsoft.VisualBasic.Switch(
                    Status = EmploymentStatus.FullTime, "Full Time",
                    Status = EmploymentStatus.PartTime, "Part Time",
                    Status = EmploymentStatus.Contractor, "Contractor",
                    Status = EmploymentStatus.Seasonal, "Seasonal")

        MsgBox("Employment Status: " & Result)

        Return 0
    End Function

End Module

This would produce:

Switch

In a true If...Then...ElseIf...ElseIf condition, we saw that there is a possibility that none of the conditions would fit, in which case you can add a last Else statement. The Switch() function also supports this situation if you are using a number, a character, or a string. To provide this last alternative, instead of a ConditionXToCheck expressionk, enter True, and include the necessary statement. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim Status As UShort
        Dim Result As String

        Status = 12

        Result = Microsoft.VisualBasic.Switch(
                    Status = 1, "Full Time",
                    Status = 2, "Part Time",
                    Status = 3, "Contractor",
                    Status = 4, "Seasonal",
                    True, "Unknown")

        MsgBox("Employment Status: " & Result)

        Return 0
    End Function

End Module

This would produce:

Switch

Remember that you can also use True with a character. Here is an example:

Module Exercise

    Public Function Main() As Integer
        Dim Gender As Char
        Dim Result As String

        Gender = "H"

        Result = Microsoft.VisualBasic.Switch(
                    Gender = "f", "Female",
                    Gender = "F", "Female",
                    Gender = "m", "Male",
                    Gender = "M", "Male",
                    True, "Unknown")

        MsgBox("Gender: " & Result)

        Return 0
    End Function

End Module

This would produce:

Switch

Practical LearningPractical Learning: Using the Switch() Function

  1. To use the Switch() function, change the document as follows:
    Module BethesdaCarRental
        Private Function GetEmployeeName(ByVal EmplNbr As Long) As String
            Dim Name As String
    
            If EmplNbr = 22804 Then
                Name = "Helene Mukoko"
            ElseIf EmplNbr = 92746 Then
                Name = "Raymond Kouma"
            ElseIf EmplNbr = 54080 Then
                Name = "Henry Larson"
            ElseIf EmplNbr = 86285 Then
                Name = "Gertrude Monay"
            Else
                Name = "Unknown"
            End If
    
            Return Name
        End Function
    
        Public Function Main() As Integer
            Dim EmployeeNumber As Long, EmployeeName As String
            Dim CustomerName As String
            Dim TagNumber As String, CarSelected As String
            Dim Tank As Integer, TankLevel As String
            Dim RentStartDate As Date, RentEndDate As Date
            Dim NumberOfDays As Integer
            Dim RateType As String, RateApplied As Double
            Dim OrderTotal As Double
            Dim OrderInvoice As String
    
            RateType = "Weekly Rate"
            RateApplied = 0
            OrderTotal = RateApplied
    
            EmployeeNumber =
    	  CLng(console.write("Employee number (who processed this order): ",
                                           "Bethesda Car Rental", "00000"))
    
            EmployeeName = GetEmployeeName(EmployeeNumber)
    
            CustomerName = console.write("Enter Customer Name: ",
                                           "Bethesda Car Rental", "John Doe")
    
            TagNumber = console.write("Enter the tag number of the car to rent: ",
                                           "Bethesda Car Rental", "000000")
    
            CarSelected = Microsoft.VisualBasic.Switch(
                        TagNumber = "297419", "BMW 335i",
                        TagNumber = "485M270", "Chevrolet Avalanche",
                        TagNumber = "247597", "Honda Accord LX",
                        TagNumber = "924095", "Mazda Miata",
                        TagNumber = "772475", "Chevrolet Aveo",
                        TagNumber = "M931429", "Ford E150XL",
                        TagNumber = "240759", "Buick Lacrosse",
                        True, "Unidentified Car")
    
            Tank = CInt(console.write("Enter Tank Level: " )
                                 "1. Empty" )
                                 "2. 1/4 Empty" )
                                 "3. 1/2 Full" )
                                 "4. 3/4 Full" )
                                 "5. Full",
                                 "Bethesda Car Rental", 1))
            TankLevel = Choose(Tank, "Empty", "1/4 Empty",
    			   "1/2 Full", "3/4 Full", "Full")
    
            RentStartDate = CDate(console.write("Enter Rent Start Date: ",
                                           "Bethesda Car Rental", #1/1/1900#))
            RentEndDate = CDate(console.write("Enter Rend End Date: ", _
                                           "Bethesda Car Rental", #1/1/1900#))
            NumberOfDays = DateDiff(DateInterval.Day, RentStartDate, RentEndDate)
    
            RateApplied = CDbl(console.write("Enter Rate Applied: ", _
                                           "Bethesda Car Rental", 0))
    
            OrderInvoice = "===========================" )
                      "=//= BETHESDA CAR RENTAL =//=" )
                      "==-=-= Order Processing =-=-==" )
                  "------------------------------------------------" )
                      "Processed by: " & vbTab & EmployeeName )
                      "Processed for: " & vbTab & CustomerName )
                  "------------------------------------------------" )
                      "Car Selected: " )
                      vbTab & "Tag #: " & vbTab & TagNumber )
                      vbTab & "Car: " & vbTab & CarSelected )
                      vbTab & "Tank: " & vbTab & TankLevel )
                  "------------------------------------------------" )
                      "Start Date: " & vbTab & RentStartDate )
                      "End Date: " & vbTab & RentEndDate )
                      "Nbr of Days: " & vbTab & NumberOfDays )
                  "------------------------------------------------" )
                      "Rate Type: " & vbTab & RateType )
                      "Rate Applied: " & vbTab & RateApplied )
                  "Order Total: " & vbTab & FormatCurrency(OrderTotal) )
                      "==========================="
    
            MsgBox(OrderInvoice,
                      MsgBoxStyle.Information Or MsgBoxStyle.OkOnly,
                   "Bethesda Car Rental")
            Return 0
        End Function
    
    End Module
  2. Eexecute the application
  3. Enter the employee number as 86285, the customer name as Genevieve H. Gomoore, the tag number as 924095, the tank level as 3, the start date as 10/22/2008, the end date as 10/31/2008, and the rate applied 55.50
     
    Car Rental
  4. Close the message box and the DOS window to return to your programming environment
 

Previous Copyright © 2008-2026, FunctionX Tueday 15 August 2024 Next