当我尝试添加integer.tryparse
来处理无效输入以及消息读取"无效输入"时,似乎无法使我的代码正常工作。例如,如果数字是字母而不是数字。以下是我到目前为止的情况:
Public Class Form1
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Answer.Text = ""
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
Dim iNum, iSum As Double
Dim isPrime As Boolean = False
iNum = Integer.Parse(TextBox1.Text)
For i = 2 To Math.Sqrt(iNum) Step 1
iSum = iNum Mod i
If (iSum = 0) Then
isPrime = True
Exit For
End If
Next
If isPrime Then
Answer.Text = "Is Not Prime"
Else
Answer.Text = "Is Prime"
End If
End Sub
End Class
答案 0 :(得分:0)
这应该这样做:
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
Dim iNum, iSum As Double
Dim isPrime As Boolean = False
If Not Integer.TryParse(TextBox1.Text, iNum)
Answer.Text = "invalid input"
Else
For i = 2 To Math.Sqrt(iNum) Step 1
iSum = iNum Mod i
If (iSum = 0) Then
isPrime = True
Exit For
End If
Next
If isPrime Then
Answer.Text = "Is Not Prime"
Else
Answer.Text = "Is Prime"
End If
End If
End Sub