如何让用户输入一个数字,如果用户输入一个字母,它会返回一个错误 - VB.net



我想确保用户输入一个介于 1 和 9 之间的数字,这很容易,但我也想确保如果用户输入说"hello",它会返回一个错误并让用户重试,无论是无限还是一定次数

我一直在使用带有 while 语句的 Try Catch 来确保用户确实输入了一个数字,它确实在哪些地方工作,但返回错误。

Ans = Console.ReadLine
While Ans < 1 Or Ans > 9
Try
Console.WriteLine("Error, enter a number between 1 and 9")
Ans = Console.ReadLine
Catch
Console.WriteLine("That is not a number between 1 and 9")
End Try
End While

Int32.TryParse 方法允许您更好地控制用户输入,而无需昂贵的异常处理程序。简单地说,如果输入不是数字,则该方法返回 false。代码稍微复杂一些,因为您选择不接受大于 9 的数字

Dim num as Integer
Do 
Console.WriteLine("Enter a number between 1 and 9")
Dim Ans as String = Console.ReadLine
if Not Int32.TryParse(Ans, num) OrElse num > 9 Then
Console.WriteLine("That is not a number between 1 and 9")
End If
While num < 1 OrElse num > 9
Console.WriteLine($"Entered Number is {num}")

Steve 是对的,但只是为了向您展示如何使用 IsNumeric 以及如何给出不同的错误:

If IsNumeric(ans) Then
If ans > 1 AndAlso ans < 9 Then
'it's a number and it's between 1 and 9
Else
'it's a number but NOT between 1 and 9
End If
Else
'not a number
End If

最新更新