2015-11-06 48 views
-1

好吧,所以我真的不知道如何做到這一點,但是如何防止崩潰,當它要求一個整數值,並且用戶給它一個字符串?防止在VB中輸入一個字符串作爲整數

下面是一些示例代碼;

private sub userInput() 
    dim userInputNum As Integer 
    userInputNum = InputBox("Enter a number.") 
end sub 

而且,如果用戶輸入文本,它只會崩潰。所以我想知道是否有人有解決方案?

謝謝,我會很感激。

回答

3

使用Integer.TryParse

Dim userInputNum As Integer 

Dim noInput = Console.ReadLine 

If Integer.TryParse(noInput, userInputNum) Then 
    Console.WriteLine("Integer accepted") 
Else 
    Console.WriteLine("Please don't enter non integer values") 
End If 
+0

的[備選](http://stackoverflow.com/questions/419027/integer-tryparse-a-better-way)。 – Eminem

+1

謝謝!這工作正常! –

+0

可能希望去除昏迷(在美國等),所以你可以接受1000等。 – rheitzman

相關問題