我遇到了应用程序的问题。当计算按钮点击事件应根据用户输入的5位数邮政编码显示相应的运费。为了有效,邮政编码必须包含5位数字,前3位数字必须为" 605"或" 606"。 " 605"运费为25美元" 606为30美元。如果邮政编码无效,则显示相应的消息。
我已经开始检查" 605"的邮政编码。或" 606"但如果我输入的数字少于5位,则给出零价而不是错误消息,所以我错过了一些东西。
感谢任何帮助或指导。 感谢。
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub txtZip_Enter(sender As Object, e As EventArgs) Handles txtZip.Enter
txtZip.SelectAll()
End Sub
Private Sub txtZip_TextChanged(sender As Object, e As EventArgs) Handles txtZip.TextChanged
lblShipping.Text = String.Empty
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim strZip As String
Dim dblShipping As Double
strZip = txtZip.Text
'Make sure zip code is 5 digits
If strZip.Length = 5 Then
'Calculate the shipping based on first 3 digits
If strZip Like "605##" Then
dblShipping = 25.0
ElseIf strZip Like "606##" Then
dblShipping = 30.0
Else
MessageBox.Show("Invalid ZIP code, must be 5 digits and begin with 605 or 606")
End If
End If
'display shipping charge
lblShipping.Text = dblShipping.ToString("N2")
End Sub
结束班
答案 0 :(得分:0)
您的Else
未正确缩进,因此它似乎属于外部If strZip.Lenth = 5 Then
语句而不是内部If strZip Like "505##" Then
语句。我已编辑了您的问题以更正此缩进错误。
您可以看到,您还没有为用户提供其他输入时指定代码路径,并且在.NET中,数字值在声明时默认为0
(即dblShipping
默认情况下值为0.0
,因此您看到的是零。
我建议这一点(注意早期失败的回报)
Dim lengthValid As Boolean = strZip.Length.Equals( 5 ) ' this is necessary as the = operator in VB.NET does not return a boolean value
Dim prefixValid As Boolean = strZip.StartsWith("605") OrElse strZip.StartsWith("607")
If Not lengthValid OrElse Not prefixValid Then
MessageBox.Show("Invalid ZIP code, must be 5 digits and begin with 605 or 606")
Return
Else
If strZip.StartsWith("605") Then
dblShipping = 25
Else
dblShipping = 30
End If
End If