Search code examples
vb.netvisual-studioconditional-statementscounteraccumulator

Why isn't my VB if statement working?


I'm working on my first project for my visual basic programming class. I am trying to have this condition statement say if the discount rate is .1 or (10%), then add to the count of customers who got the discount (msngFrequentFlyers) and add to the accumulator that keeps track of total discounts given (msngTotalDiscounts).

I'm very new to all this- please help! Project is due tonight.

Here's my code:

Public Class frmTaxiConsole
'Modular Variable Declaration Section
'Declares msngDiscountRate and sets inital value to -1 for testing user input
Dim msngDiscountRate As Single = -1
'Declares all counter variables
Dim msngNumberOfRides As Single
Dim msngNumberOfFrequentFlyers As Single
'Declares all accumulator variables
Dim msngRevenue As Single
Dim msngTotalDiscounts As Single
Dim msngBillableMiles As Single

If the radio button for the discount is checked:

    Private Sub radFrequentFlyer_CheckedChanged(sender As Object, e As EventArgs) Handles radFrequentFlyer.CheckedChanged
    msngDiscountRate = 0.1 'Sets discount rate to 10% upon selection of radio button
End Sub

This is the if statement that's not working, in the "Process Transaction" click event:

        If msngDiscountRate = "0.1" Then 'Checks to see if this transaction had any discount
        msngNumberOfFrequentFlyers += 1 'If so, adds 1 to the number of discounts given
        msngTotalDiscounts = msngTotalDiscounts + (sngSubTotal * msngDiscountRate) 'Also adds the discount amount to the total discounts accumulator (without making it negative)
    End If

Here's the entire code for the "Process Transaction" click event:

 Private Sub btnProcessTx_Click(sender As Object, e As EventArgs) Handles btnProcessTx.Click
    'Local Variable Declaration Section
    Dim sngMilesDriven As Single
    Dim dblOdometerStart As Double
    Dim dblOdometerEnd As Double
    Dim sngInitialFee As Single
    Dim sngPerMileFee As Single
    Dim sngMileageCharge As Single
    Dim sngSubTotal As Single
    Dim sngDiscount As Single
    Dim sngTotalDue As Single

    'Data Input + Testing Section
    'Changes all text box backcolors white, in case they had been turned red due to an error
    txtOdometerStart.BackColor = Color.White
    txtOdometerEnd.BackColor = Color.White
    txtInitialFee.BackColor = Color.White
    txtPerMileFee.BackColor = Color.White
    'Try/Catch validates user input for Inital Fee 
    Try
        'Attempts to convert user input to Single and store as a local variable
        sngInitialFee = CSng(txtInitialFee.Text)
    Catch ex As Exception
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Please enter a valid initial fee.", "Invalid Initial Fee", MessageBoxButtons.OK)
        txtInitialFee.BackColor = Color.Red
        txtInitialFee.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End Try
    'Try/Catch validates user input for Per-Mile Fee
    Try
        'Attempts to convert user input to Single and store as a local variable
        sngPerMileFee = CSng(txtPerMileFee.Text)
    Catch ex As Exception
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Please enter a valid per-mile fee.", "Invalid Per-Mile Fee", MessageBoxButtons.OK)
        txtPerMileFee.BackColor = Color.Red
        txtPerMileFee.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End Try
    'Try/Catch validates user input for starting milage
    Try
        'Attempts to convert user input to Double and store as a local variable
        dblOdometerStart = CDbl(txtOdometerStart.Text)
    Catch ex As Exception
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Please enter a valid starting milage.", "Invalid Odometer Reading", MessageBoxButtons.OK)
        txtOdometerStart.BackColor = Color.Red
        txtOdometerStart.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End Try
    'Try/Catch validates user input for ending milage
    Try
        'Attempts to convert user input to Double and store as a local variable
        dblOdometerEnd = CDbl(txtOdometerEnd.Text)
    Catch ex As Exception
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Please enter a valid ending milage.", "Invalid Odometer Reading", MessageBoxButtons.OK)
        txtOdometerEnd.BackColor = Color.Red
        txtOdometerEnd.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End Try
    'If statement ensures Inital Fee is a positive number
    If sngInitialFee < 0 Then
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Initial Fee cannot be negative.", "Invalid Inital Fee", MessageBoxButtons.OK)
        txtInitialFee.BackColor = Color.Red
        txtInitialFee.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End If
    'If statement ensures Per-Mile Fee is a positive number
    If sngPerMileFee < 0 Then
        'If error occurs, displays a messagebox, changes background color of relavent text box, and exits sub.
        MessageBox.Show("Per-Mile Fee cannot be negative.", "Invalid Per-Mile Fee", MessageBoxButtons.OK)
        txtPerMileFee.BackColor = Color.Red
        txtPerMileFee.Focus() 'Focuses in text box where error occured so user can fix
        Exit Sub
    End If
    'If statement checks to make sure starting milage is smaller number than ending milage
    If dblOdometerEnd <= dblOdometerStart Then
        'If ending milage is smaller number than starting milage, displays a messagebox and exits sub.
        MessageBox.Show("Your ending mileage cannot be less than or equal to your starting mileage. Please check your odometer readings.", "Invalid Odometer Reading", MessageBoxButtons.OK)
        txtOdometerStart.Focus() 'Focuses in starting odometer reading text box so user can fix
        Exit Sub
    End If
    'If statement checks to make sure both odometer readings are positive numbers.
    If dblOdometerEnd < 0 Or dblOdometerStart < 0 Then
        'If either odometer reading is negative, displays a messagebox and exits sub.
        MessageBox.Show("Both your odometer readings must be positive numbers. Please check your odometer readings.", "Invalid Odometer Reading", MessageBoxButtons.OK)
        txtOdometerStart.Focus() 'Focuses in starting odometer reading text so user can fix
        Exit Sub
    End If
    'If statement checks to ensure user has seleted one of the two radio buttons
    If msngDiscountRate = -1 Then
        'If msngDiscountRate is the same as the initial value, neither option has been chosen, an error message is shown, and sub exited.
        MessageBox.Show("Please choose a frequent flyer status.", "Frequent Flyer?", MessageBoxButtons.OK)
        Exit Sub
    End If
    'Calculations Section
    sngMilesDriven = CSng(dblOdometerEnd - dblOdometerStart) 'Subtracts starting mileage from ending mileage, converts to single, stores as var sngMilesDriven
    sngMileageCharge = sngMilesDriven * sngPerMileFee 'Multiplies the miles driven by the per-mile fee and stores as var sngMileageCharge
    sngSubTotal = sngMileageCharge + sngInitialFee 'Adds the milage charge to the initial fee, stores as var sngSubTotal
    sngDiscount = sngSubTotal * msngDiscountRate * -1 'Multiplies subtotal by discount rate, makes negative, stores as var sngDiscount
    sngTotalDue = sngSubTotal + sngDiscount 'Subtracts discounts from subtotal, stores as var sngTotalDue
    'Counter and Accumulator Operations
    msngNumberOfRides += 1 'Adds 1 to the number of rides given
    If msngDiscountRate = "0.1" Then 'Checks to see if this transaction had any discount
        MsgBox(msngDiscountRate)
        msngNumberOfFrequentFlyers += 1 'If so, adds 1 to the number of discounts given
        msngTotalDiscounts = msngTotalDiscounts + (sngSubTotal * msngDiscountRate) 'Also adds the discount amount to the total discounts accumulator (without making it negative)
    End If
    msngRevenue = msngRevenue + sngTotalDue 'Adds the total due for current transaction to revenue accumulator
    msngBillableMiles = msngBillableMiles + sngMilesDriven 'Adds miles from this transaction to running total

    'Output Section
    'Displays above calculations in respective labels and formats as currency if neccecary.
    lblMilesDrivenOutput.Text = sngMilesDriven
    lblSumInitialFeeOutput.Text = FormatCurrency(sngInitialFee) 'Formats sngInitialFee as currency and displays in lblSumInitialFeeOutput
    lblSumMilageChargeOutput.Text = FormatCurrency(sngMileageCharge)
    lblSumSubTotalOutput.Text = FormatCurrency(sngSubTotal)
    lblSumDiscountOutput.Text = FormatCurrency(sngDiscount)
    lblSumTotalDueOutput.Text = FormatCurrency(sngTotalDue)
    'Displays all counter and accumulator variables after they are updated
    lblTotalRidesOutput.Text = msngNumberOfRides
    lblFrequentFlyersOutput.Text = msngNumberOfFrequentFlyers
    lblRevenueOutput.Text = FormatCurrency(msngRevenue)
    lblTotalDiscountsOutput.Text = FormatCurrency(msngTotalDiscounts)
    lblBillableMilesOutput.Text = msngBillableMiles


End Sub

Solution

  • Firstly as mentioned above you'll need to remove the quotes around the 0.1 in your if statement, this won't work as it's comparing a number to a string.

    I'm no expert on floating-point arithmetic, but as Plutonix alludes to, I think the problem when you tried it without quotes is that the 0.1 you're comparing your msngDiscountRate in the if statement defaults to a Double, whereas you've declared your variable as a Single, so the if statement evaluates to false.

    You could either declare your msngDiscountRate variable as Double instead, or cast the 0.1 to a Single to get around it. These simple examples might help -

        'Variable declared as a Single, compared to 0.1 (a Double) - If statement evaluates to false
        Dim msngDiscountRateExample1 As Single = -1
        msngDiscountRateExample1 = 0.1
    
        If msngDiscountRateExample1 = 0.1 Then
            Debug.Print(msngDiscountRateExample1.ToString)
        End If
    
        'Variable declared as a Double, compared to 0.1 (another Double) - If statement evaluates to true
        Dim msngDiscountRateExample2 As Double = -1
        msngDiscountRateExample2 = 0.1
    
        If msngDiscountRateExample2 = 0.1 Then
            Debug.Print(msngDiscountRateExample2.ToString)
        End If
    
        'Variable declared as a Single, compared to 0.1 (a Double) which is *cast* as a Single - If statement evaluates to true
        Dim msngDiscountRateExample3 As Single = -1
        msngDiscountRateExample3 = 0.1
    
        If msngDiscountRateExample3 = CSng(0.1) Then
            Debug.Print(msngDiscountRateExample3.ToString)
        End If