[英]An 'if' statement with numbers
I just bought a pool, and I am developing a log program to measure the chemicals every day. 我刚买了一个游泳池,并且正在开发一个日志程序来每天测量化学物质。 Rather than looking up what the chemical is supposed to be, I will build it into my program, the below statement isn't working properly. 下面的语句不能正常工作,而不是查找化学物质是什么,而是将其构建到程序中。 Even if I put in a 6, Level Perfect
still shows up in my label: 即使我输入6, Level Perfect
仍会出现在我的标签中:
If FCI__Free_Cholorine_ppmTextBox.Text < "1" Then
lbfci.Text = "Level Too low"
ElseIf FCI__Free_Cholorine_ppmTextBox.Text > "0" Then
lbfci.Text = "Level Perfect"
ElseIf FCI__Free_Cholorine_ppmTextBox.Text <= "4" Then
lbfci.Text = "Level Perfect"
ElseIf FCI__Free_Cholorine_ppmTextBox.Text > "4" Then
lbfci.Text = "Level Too High"
End If
Ideally you should parse the contents of the textbox as an Integer first using the Integer.TryParse
method in order to cut out any mistakes the user may have made entering the number into the textbox. 理想情况下,您应该首先使用Integer.TryParse
方法将文本框的内容解析为Integer,以消除用户可能在文本框中输入数字而犯的任何错误。
' First initialize a String variable and Trim any whitespace
Dim s As String = FCI__Free_Cholorine_ppmTextBox.Text.ToString().Trim()
Dim num As Integer
' Integer.TryParse returns True if it has successfully parsed the String into an Integer
If Integer.TryParse(s, num) Then
If num > 4 Then
lbfci.Text = "Level Too High"
ElseIf num > 0 Then
lbfci.Text = "Level Perfect"
Else
lbfci.Text = "Level Too low"
End If
Else
lbfci.Text = "Not a number"
End If
Convert the strings to numbers then use an if / elseif. 将字符串转换为数字,然后使用if / elseif。 The order of checks is important 检查的顺序很重要
Private Sub FCI__Free_Cholorine_ppmTextBox_TextChanged(sender As Object, e As EventArgs) _
Handles FCI__Free_Cholorine_ppmTextBox.TextChanged
Dim lvl As Decimal
If Decimal.TryParse(FCI__Free_Cholorine_ppmTextBox.Text, lvl) Then
'the order of checking is important
If lvl > 4 Then '5,6,7,etc.
lbfci.Text = "Level Too High"
ElseIf lvl > 0 Then '1,2,3,4
lbfci.Text = "Level Perfect"
Else
lbfci.Text = "Level Too low"
End If
Else
lbfci.Text = "Numbers only"
End If
End Sub
This demonstrates why string comparisons are not a good idea in this case 这说明了为什么在这种情况下字符串比较不是一个好主意
Dim s As String = "10"
Dim s1 As String = "4"
If s > s1 Then
Stop
End If
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.