2014-12-07 63 views
0

我正在編寫一個程序,檢查用戶是否輸入了整數,此時它適用於除小數點以外的所有數據。即使我已經將它聲明爲一個整數,但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 
+3

'Console.ReadLine'返回一個字符串。你的代碼需要驗證並轉換它。 '選擇嚴格打開'將有助於此 – Plutonix 2014-12-07 14:50:10

+1

另一個咬傷灰塵。 [_Option Strict Off_](http://msdn.microsoft.com/en-us/library/zcd4xwzs.aspx)再次殺死 – Steve 2014-12-07 14:54:14

回答

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