Значения не передаются в функцию в Visual Basic - PullRequest
0 голосов
/ 03 апреля 2019

Это домашнее задание для создания приложения, которое рассчитывает арендную плату за загородный дом. Все расчеты должны быть выполнены с помощью функций. Всякий раз, когда я запускаю программу, все выходы возвращают ноль ($ 0.00). Я могу сказать, что это потому, что «0» передается в функции вместо значения, полученного из пользовательского ввода. Так как функция проверки смогла получить эти входные данные очень хорошо, я не знаю, в чем проблема.

Я попытался реструктурировать свои функции из FUNCTION_NAME (PARAM1, PARAM2 ...) в VARIABLE = FUNCTION_NAME (PARAM1, PARAM2 ...), но это не сработало.

Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click

        'Declare variables and constants
        Dim strFirstName As String
        Dim strLastName As String
        Dim strPhoneNumber As String
        Dim strEmailAddress As String
        Dim intDaysToRent As Integer
        Dim strSeason As String
        Dim strBuyerState As String
        Dim dblSubTotal As Double
        Dim dblTaxAmount As Double
        Dim dblFinalTotal As Double

        Const dblOffSeason As Double = 50
        Const dblPeakSeason As Double = 150
        Const dblStandardSeason As Double = 100
        Const dbl14DayDiscount As Double = 0.95
        Const dbl30DayDiscount As Double = 0.9
        Const dblTaxRate As Double = 0.1

        'Validate inputs
        If ValidateInputs(strFirstName, strLastName, strPhoneNumber, strEmailAddress, intDaysToRent, strSeason, strBuyerState) = True Then

            'Calculate subtotal
            dblSubTotal = CalculateSubTotal(intDaysToRent, strSeason, dbl14DayDiscount, dbl30DayDiscount, dblSubTotal)

            'Calculate tax amount
            dblTaxAmount = CalculateTaxAmount(dblSubTotal, strBuyerState, dblTaxRate, dblTaxAmount)


            'Calculate final total
            dblFinalTotal = CalculateFinalTotal(dblSubTotal, dblTaxAmount, dblFinalTotal)
____________________________________________________________

 Function ValidateInputs(ByVal FirstName As String, ByVal LastName As String, ByVal PhoneNumber As String, ByVal EmailAddress As String, ByVal DaysToRent As Integer, ByVal Season As String, ByVal BuyerState As String)

        'Main validation procedure
        If ValidateFirstName(FirstName) = True Then
            If ValidateLastName(LastName) = True Then
                If ValidatePhoneNumber(PhoneNumber) = True Then
                    If ValidateEmailAddress(EmailAddress) = True Then
                        If ValidateDaysToRent(DaysToRent) = True Then
                            If ValidateSeason(Season) = True Then
                                If ValidateBuyerState(BuyerState) = True Then
                                    Return True
                                Else Return False
                                End If
                            Else Return False
                            End If
                        Else Return False
                        End If
                    Else Return False
                    End If
                Else Return False
                End If
            Else Return False
            End If
        Else
            Return False
            Exit Function
        End If

    End Function
____________________________________________________________
    'First name validation subroutine
    Function ValidateFirstName(ByRef FirstName As String) As Boolean

        'Check that input exists
        If txtFirstName.Text Is String.Empty Then
            txtFirstName.BackColor = Color.Yellow
            txtFirstName.Focus()
            MessageBox.Show("Please enter the renter's first name.")
            Return False
            Exit Function

            'Check that input is a valid string
        ElseIf IsNumeric(txtFirstName.Text) Then
            txtFirstName.BackColor = Color.Yellow
            txtFirstName.Focus()
            MessageBox.Show("Please enter letters only.")
            Return False
            Exit Function
        Else
            FirstName = txtFirstName.Text
            Return True
        End If

    End Function
____________________________________________________________
    'Last name validation subroutine
    Function ValidateLastName(ByRef LastName As String) As Boolean

        'Check that input exists
        If txtLastName.Text Is String.Empty Then
            txtLastName.BackColor = Color.Yellow
            txtLastName.Focus()
            MessageBox.Show("Please enter the renter's last name.")
            Return False
            Exit Function

            'Check that input is valid string
        ElseIf IsNumeric(txtLastName.Text) Then
            txtLastName.BackColor = Color.Yellow
            txtLastName.Focus()
            MessageBox.Show("Please enter letters only.")
            Return False
            Exit Function
        Else
            LastName = txtLastName.Text
            Return True
        End If

    End Function
____________________________________________________________
    'Validate phone number subroutine
    Function ValidatePhoneNumber(ByRef PhoneNumber As String) As Boolean

        'Check that input exists
        If txtPhoneNumber.Text Is String.Empty Then
            txtPhoneNumber.BackColor = Color.Yellow
            txtPhoneNumber.Focus()
            MessageBox.Show("Please enter the renter's phone number.")
            Return False
            Exit Function

            'Check that input is valid string
        ElseIf IsNumeric(txtPhoneNumber.Text) Then
            PhoneNumber = txtPhoneNumber.Text
            Return True
        Else
            txtPhoneNumber.BackColor = Color.Yellow
            txtPhoneNumber.Focus()
            MessageBox.Show("Please enter numbers only.")
            Return False
            Exit Function
        End If

    End Function
____________________________________________________________
    'Validate email address subroutine
    Function ValidateEmailAddress(ByRef EmailAddress As String) As Boolean

        'Check that input exists
        If txtEmail.Text Is String.Empty Then
            txtEmail.BackColor = Color.Yellow
            txtEmail.Focus()
            MessageBox.Show("Please enter the renter's email address.")
            Return False
            Exit Function
        Else
            EmailAddress = txtEmail.Text
            Return True
        End If

    End Function
____________________________________________________________
    'Validate days to rent subroutine
    Function ValidateDaysToRent(ByVal DaysToRent As String) As Boolean

        'Check that input exists
        If txtDaysRented.Text Is String.Empty Then
            txtDaysRented.BackColor = Color.Yellow
            txtDaysRented.Focus()
            MessageBox.Show("Please enter the number of days the condo will be rented.")
            Return False

            'Check that input is valid string
        ElseIf IsNumeric(txtDaysRented.Text) Then
            DaysToRent = txtDaysRented.Text
            Return True
        Else
            txtDaysRented.BackColor = Color.Yellow
            txtDaysRented.Focus()
            MessageBox.Show("Please enter numbers only.")
            Return False
            Exit Function
        End If

    End Function
____________________________________________________________
    'Season validation subroutine
    Function ValidateSeason(ByVal Season As String) As Boolean

        'Check that input exists
        If cboSeason.Text Is String.Empty Then
            cboSeason.BackColor = Color.Yellow
            cboSeason.Focus()
            MessageBox.Show("Please enter the season the condo will be rented in.")
            Return False
            Exit Function
        Else
            Season = cboSeason.Text
            Return True
        End If

    End Function
____________________________________________________________
    'State validation subroutine
    Function ValidateBuyerState(ByVal BuyerState As String) As Boolean

        'Check that input exists
        If cboState.Text Is String.Empty Then
            cboState.BackColor = Color.Yellow
            cboState.Focus()
            MessageBox.Show("Please enter the season the renter's state of residence.")
            Return False
            Exit Function
        Else
            BuyerState = cboState.Text
            Return True
        End If

    End Function
____________________________________________________________
  'Subtotal Calcultion Function
    Function CalculateSubTotal(ByVal DaysToRent As Integer, ByRef Season As String, ByVal Discount14 As Double, ByVal Discount30 As Double, ByRef Subtotal As Double) As Double

        'Declare variable
        Dim dblSubTotal As Double
        Dim dblSeasonRate As Double
        Dim strSeason As String

        cboSeason.Text = strSeason

        'Determine season rate
        If Season = "Off Season" Then
            dblSeasonRate = 50
        ElseIf Season = "Peak Season" Then
            dblSeasonRate = 150
        ElseIf Season = "Standard Season" Then
            dblSeasonRate = 100
        End If

        'Calculate subtotal
        dblSubTotal = DaysToRent * dblSeasonRate

        'Calculate discount (if applicable)
        If DaysToRent > 14 And DaysToRent < 31 Then
            dblSubTotal = Subtotal * Discount14
        ElseIf DaysToRent > 30 Then
            dblSubTotal = Subtotal * Discount30
        End If

        Return dblSubTotal

    End Function
____________________________________________________________

    'Tax amount calculation function
    Function CalculateTaxAmount(ByVal Subtotal As Double, ByVal State As String, ByVal TaxRate As Double, ByRef TaxAmount As Double) As Double

        'Calculate tax rate
        If State = "Florida" Then
            TaxAmount = 0
        Else
            TaxAmount = Subtotal * TaxRate
        End If

        Return TaxAmount

    End Function
____________________________________________________________

    'Final total calculation function
    Function CalculateFinalTotal(ByVal Subtotal As Double, ByVal TaxAmount As Double, ByRef FinalTotal As Double) As Double

        'Calculate final total
        FinalTotal = Subtotal + TaxAmount

        Return FinalTotal

    End Function

1 Ответ

1 голос
/ 03 апреля 2019

Вы передаете параметры в ValidateInputs, используя byval. Это создает копию этих переменных в функции, и именно этим копиям присваиваются значения отдельным функциям проверки. Переменные в btnSubmit_Click остаются в качестве значений по умолчанию, и именно они передаются в функции расчета.

Изменение используемых параметров byref остановит это:

Function ValidateInputs(ByRef FirstName As String, ByRef LastName As String, ByRef PhoneNumber As String, ByRef EmailAddress As String, ByRef DaysToRent As Integer, ByRef Season As String, ByRef BuyerState As String)
...