我正在使用 Integer.TryParse 方法来验证用户输入在我的程序中是数字还是非数字。1)如果用户输入的是数字,程序将继续并验证用户输入的范围是从 0 到 9。 2)如果用户输入的是非数字输入,程序将显示消息“无效输入”并要求用户从头开始。
以下是我的编码:Sub Main()
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
Dim index As Integer
Dim number As Integer
Dim reEnter As Boolean = True
Console.WriteLine("Please enter 7 integers: ")
Console.WriteLine("<ATTENTION: FROM 0 TO 9 ONLY>")
Console.WriteLine()
While reEnter
For index = 0 To 6
Console.WriteLine("Please enter the integer no." & "{0}" & " : ", index + 1) 'Prompt user to enter 7 integers.
sevenNumbers(index) = Console.ReadLine() 'The 7 integers are stored in an array.
If Integer.TryParse(sevenNumbers(index), number) Then
While sevenNumbers(index) < 0 Or sevenNumbers(index) > 9
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End While
Else
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End If
reEnter = False
Next
End While
结束子
但是,当用户输入非数字输入时,程序无法继续并显示强制关闭的错误。
我试过这个
Sub Main() Dim num As Integer
Console.Write("enter num:")
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then
Console.WriteLine("valid. num = " & num)
Else
Console.WriteLine("invalid")
End If
End Sub
它确实有效,我想知道我的编码的哪一部分是错误的?
感谢帮助!!