我正在编写一个程序来检查用户是否输入了一个整数,此时它对小数点以外的所有内容起作用。尽管我已将其声明为整数,但try语句并未捕获小数作为异常。我该如何解决这个问题?
Sub Main()
Dim Test As Integer
Do
Console.WriteLine("Enter a whole number")
Try
Test = Console.ReadLine()
Exit Do
Catch ex As Exception
Console.WriteLine("You must enter a whole number")
Console.WriteLine()
Exit Try
End Try
Loop
Console.ReadLine()
End Sub
答案 0 :(得分:2)
使用TryParse
Dim number As Integer
Dim result As Boolean = Int32.TryParse(Test, number)
If result Then
Console.WriteLine("You entered {0}.", number)
Else
Console.WriteLine("You must enter a whole number")
End If