家庭作业任务是简单地允许用户输入值(字符串)“FD__”并将其与已知输入列表匹配并返回true / false。已经定义了ID并且它运行良好,当我键入一个定义为Products(2)
的ID为“FD3”时,它将返回true,如果未定义该值,它将不仅没有给出结果但是崩溃了程序,所以总的来说,真正的工作,但错误的不是。任何信息都可能有所帮助。
设计:http://i.imgur.com/bJnFAMX.png
Public Class Form1
'variables
Dim Products(9) As String
Dim Entered As String
Dim Found As Boolean
Public Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click
'Product variable array elements
Products(0) = "FD1"
Products(1) = "FD2"
Products(2) = "FD3"
Products(3) = "FD4"
Products(4) = "FD5"
Products(5) = "FD6"
Products(6) = "FD7"
Products(7) = "FD8"
Products(8) = "FD9"
Products(9) = "FD10"
'process
Entered = txtFind.Text 'define entered value as variable
Found = FindNumber() 'sub function
If Found Then
lblResult.Text = Found 'change the results
End If
End Sub
Public Function FindNumber()
'If true statements
Do While (Found = False)
If Entered = Products(0) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
ElseIf Entered = Products(1) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
ElseIf Entered = Products(2) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
ElseIf Entered = Products(3) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
ElseIf Entered = Products(4) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
ElseIf Entered = Products(5) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
ElseIf Entered = Products(6) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
ElseIf Entered = Products(7) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
ElseIf Entered = Products(8) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
ElseIf Entered = Products(9) Then
Found = True
lblResult.ForeColor = Color.LawnGreen
Else 'keeps crashing
Found = False
lblResult.ForeColor = Color.Red
End If
Loop
Return Found
End Function
End Class
答案 0 :(得分:0)
你实际上可以通过很多更少的代码来实现这一点......我会继续前进并在此时做一些批评。
'1. Functions should have return types
'2. You should pass the function what it needs to do its job
Public Function FindNumber(numberEntered As String) As Boolean
'Rather than evaluating if a condition is true or false, and then returning
'true or false, you can just directly return the condition.
Return Products.Contains(numberEntered)
End Function
然后在你的主程序中:
'This doesn't need to be a class level variable
Dim entered = txtFind.Text
'Local variables should be lowercase
Dim found = FindNumber(entered)
If found Then
'With Option Strict you can't assign a Boolean to a String...
'but you can do .ToString() instead
lblResult.Text = found.ToString()
'And this was really dependent on the result of the function...
'Also it has nothing to do with finding the number...
lblResult.ForeColor = Color.LawnGreen
Else
lblResult.ForeColor = Color.Red
End If
它看起来要长得多,但请注意这些评论,我保证这将是一个更简单(更短)的程序。
答案 1 :(得分:0)
您可以使用.contains函数优化整个代码,这个简单的用法如下:
如果是mylist.contains(" sometext")那么 '将forecolor更改为绿色 其他 '将forecolor更改为红色 结束如果
这可以缓解您的问题。