首页 > 解决方案 > 了解数据验证

问题描述

我正在为学校做一项作业,我必须验证数据输入。我的第一个问题是,当我运行代码并使用任何其他字母作为客户类型时,运行该函数不会产生错误消息。

我的第二个问题是即使注释掉了,注释掉的 Else 子句的 40% 折扣也适用。

Private Sub GetDiscountPercent(customerType As String, subtotal As Decimal,
                               ByRef discountPercent As Decimal)
    If customerType = "R" Then
        If subtotal < 100 Then
            discountPercent = 0
        ElseIf subtotal >= 100 AndAlso subtotal < 250 Then
            discountPercent = 0.1D
        ElseIf subtotal >= 250 Then
            discountPercent = 0.25D
        End If
    ElseIf customerType = "C" Then
        If subtotal < 250 Then
            discountPercent = 0.2D
        Else
            discountPercent = 0.3D
        End If
        'Else
        'discountPercent = 0.4D
    End If
End Sub

Private Sub btnExit_Click(sender As Object,
        e As EventArgs) Handles btnExit.Click
    Me.Close()
End Sub

Private Sub ClearResultBoxes(sender As Object,
        e As EventArgs) _
        Handles txtCustomerType.TextChanged, txtSubtotal.TextChanged
    txtDiscountPercent.Text = ""
    txtDiscountAmount.Text = ""
    txtTotal.Text = ""
End Sub

Function IsValidCustomerType() _
As Boolean
    If IsValidCustomerType = "R" Then
        MessageBox.Show("Customer Type has to be R or C or T", "Entry Error")
        txtCustomerType.Select()
        Return False
    Else
        Return True
    End If
    If Not IsValidCustomerType = "C" Then
        MessageBox.Show("Customer Type has to be R or C or T", "Entry Error")
        txtCustomerType.Select()
        Return False
    Else
        Return True
    End If
End Function
End Class

标签: vb.net

解决方案


我正在为学校做一项作业,我必须验证数据输入。我的第一个问题是,当我运行代码并使用任何其他字母作为客户类型时,运行该函数不会产生错误消息。

推测这是错误的:

Function IsValidCustomerType() _
As Boolean
    If IsValidCustomerType = "R" Then
       ^^^^^^^^^^^^^^^^^^^^^^^^^
        MessageBox.Show("Customer Type has to be R or C or T", "Entry Error")
        txtCustomerType.Select()
        Return False
    Else
        Return True
    End If
    If Not IsValidCustomerType = "C" Then
        MessageBox.Show("Customer Type has to be R or C or T", "Entry Error")
        txtCustomerType.Select()
        Return False
    Else
        Return True
    End If
End Function
End Class

您已声明此函数返回一个布尔值。您不能以有意义的方式将其与字符串进行比较,如果选项 strict 开启,它甚至不会编译。

即使您可以将布尔值与字符串进行比较,这也是错误的逻辑。如果您设法使 Type = C,那么代码将永远无法进行该检查,因为它返回 true 或 false(在本例中为 false),因为 C 不是 R,所以虽然 C 有效,但您永远不会检查它是否存在C,因为代码只会考虑它是否是 R

您需要停止编码并使用笔和纸写出您的算法

我的第二个问题是即使注释掉了,注释掉的 Else 子句的 40% 折扣也适用。

我要在这里说因为这段代码是错误的,或者因为其他地方的一些其他编译器错误,你会看到一个对话框,上面写着“有构建错误。你想运行最后一次成功的构建吗?” 并且您说“是”,并且您正在运行该代码未注释掉的应用程序版本..


推荐阅读