我有一个应用程序,检查用户的输入是否在A - F的文本范围内,我的代码工作正常,但我只是认为应该有一个更短的方法来做这个,可能在一行?
以下是代码:
Private Sub ResultButton_Click(sender As Object, e As EventArgs) Handles ResultButton.Click
Dim Range_A As Integer, Range_B As Integer, Range_C As Integer,
Range_D As Integer, Range_E As Integer, Range_F As Integer, Range_Check As Integer
Range_A = Integer.Parse(inputTextBox.Text)
Range_B = Integer.Parse(inputTextBox.Text)
Range_C = Integer.Parse(inputTextBox.Text)
Range_D = Integer.Parse(inputTextBox.Text)
Range_E = Integer.Parse(inputTextBox.Text)
Range_F = Integer.Parse(inputTextBox.Text)
Range_Check = Integer.Parse(inputTextBox.Text)
If Range_Check >= 101 Or Range_Check < 0 Then
MessageBox.Show(" Only values within 0 and 100 are allowed, please type a number within this range.")
End If
If Range_F >= 0 And Range_F <= 39 Then
MessageBox.Show(" " & Range_F & " is within the F Range")
Exit Sub
End If
If Range_E >= 40 And Range_E <= 44 Then
MessageBox.Show(" " & Range_E & " is within the E Range")
Exit Sub
End If
If Range_D >= 45 And Range_D <= 49 Then
MessageBox.Show(" " & Range_D & " is within the D Range")
Exit Sub
End If
If Range_C >= 50 And Range_C <= 59 Then
MessageBox.Show(" " & Range_C & " is within the C Range")
Exit Sub
End If
If Range_B >= 60 And Range_B <= 69 Then
MessageBox.Show(" " & Range_B & " is within the B Range")
Exit Sub
End If
If Range_A >= 70 And Range_A <= 100 Then
MessageBox.Show(" " & Range_A & " is within the A Range")
Exit Sub
End If
End Sub
我正在重复相同的Integer.Parse
语句,上次我检查时并不总是一个好主意,如何优化这些代码行?
答案 0 :(得分:2)
Select Case Integer.Parse(inputTextBox.Text)
Case 70 To 100
MessageBox.Show("Your Grade is A")
Case Is > 60
MessageBox.Show("Your Grade is B")
Case Is > 50
MessageBox.Show("Your Grade is C")
Case Is > 45
MessageBox.Show("Your Grade is D")
Case Is > 40
MessageBox.Show("Your Grade is E")
Case Is > 0
MessageBox.Show("Your Grade is F")
Case Else
MessageBox.Show("Only values within 0 and 100 are allowed, please type a number within this range.")
End Select
答案 1 :(得分:1)
Dim range As String = ""
If Not Integer.TryParse(inputTextBox.Text, theValue) Then
MessageBox.Show("Enter only numerals, please")
Exit Sub
End if
' if integer,.tryparse is true then theValue will have the result
Select Case theValue
Case Is > 100, Is < 1
' do err msg
Case 0 to 39
range = "A"
Case 40 To 50
range = "B"
' etc...or:
Case 41 to 44
MessageBox.Show(" " & inputTextBox.Text & " is within the E Range")
End Select
2个变量,1解析或只评估值并显示消息,如上一个。将这些保存到变量的主要原因是,如果您需要其他地方的结果
答案 2 :(得分:1)
您只需解析输入文本框一次,并使用普通范围替换 Range_A,Range_B,Range_Check等的每个实例,因此:
Dim Range As Integer
Range = Integer.Parse(inputTextBox.Text)
If Range >= 101 Or Range < 0 Then
MessageBox.Show(" Only values within 0 and 100 are allowed, please type a number within this range.")
End If
If Range >= 0 And Range <= 39 Then
MessageBox.Show(" " & Range & " is within the F Range")
End If
...等所有检查。拥有单独的名称并没有做任何事情。