vb.net - 了解数据验证
问题描述
我正在为学校做一项作业,我必须验证数据输入。我的第一个问题是,当我运行代码并使用任何其他字母作为客户类型时,运行该函数不会产生错误消息。
我的第二个问题是即使注释掉了,注释掉的 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
解决方案
我正在为学校做一项作业,我必须验证数据输入。我的第一个问题是,当我运行代码并使用任何其他字母作为客户类型时,运行该函数不会产生错误消息。
推测这是错误的:
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% 折扣也适用。
我要在这里说因为这段代码是错误的,或者因为其他地方的一些其他编译器错误,你会看到一个对话框,上面写着“有构建错误。你想运行最后一次成功的构建吗?” 并且您说“是”,并且您正在运行该代码未注释掉的应用程序版本..
推荐阅读
- html - 做什么
% 以 CSS 长度表示,例如 100%25 - python - 在 pygame 中播放音频的问题
- asp.net-core - Oracle Odp.Net Core 非异步解决方法 aspnet webapi core 5
- c++ - C++ 静态反射 TS:它会支持按名称分配/调用吗?
- python - 遍历python中的yaml列表
- firebase - 运行“flutter packages get”命令时出错
- php - 在 WooCommerce 中显示来自客户订单的账单电子邮件 我的帐户 编辑地址
- python - 我想将一个变量从一个类传递到另一个类,并使用 python 和 tkinter 在 Label 小部件中使用它
- relationship - 表之间的关系问题,以及由此导致的数据过载
- javascript - 当对象属性的属性发生更改时,如何重新渲染 litelement 组件?