验证以确保输入的值是整数

时间:2019-03-27 20:22:15

标签: vb.net validation

我想要一种验证方法,以确保输入的值有效,它必须是整数(可以包含负数)并且不能为空。我已经编写了此代码,但是不正确,请有人帮我。谢谢

If (b <> Integer Or " ") Then
            Console.WriteLine("Value entered must be a number")
        End If


new code:
Line98:
        Console.WriteLine("Please input the value of, B:")
        b = Console.ReadLine()
        If Not Integer.TryParse(b, New Integer) Then
            Console.WriteLine("Value entered must be a number")
            GoTo Line98
        End If

所以我使用了一条select语句,并且如果用户输入“ abckak”的任何非数字数据,我都会收到错误未处理的异常:System.InvalidCastException:从字符串“ gakjdg”到“ Integer”类型的转换无效。 >

如何解决,这是我的代码的一个简短示例

 Console.WriteLine("..........Main Menu..........")
            Console.WriteLine("Please input 1 ")
            Console.WriteLine("Please input 2")
            Console.WriteLine("Please input 3 ")
            Console.WriteLine("Please input 4 ")
            Console.WriteLine("Please input 5 for Help")
            Console.WriteLine("Please input 6 to Exit")

            Console.WriteLine("Please enter your choice: ")

            Choice = Console.ReadLine()
            Select Case Choice

case1; etc

Case Else
                    Console.WriteLine("Error: " & Choice & " is not a option, Please try again")

1 个答案:

答案 0 :(得分:0)

查看Integer.TryParse,它将尝试将字符串解析为整数(如果可以),如果不能则不会抛出异常...

 Dim b As Integer
 Console.WriteLine("Please input the value of, B:")            
 If Not Integer.TryParse(Console.ReadLine(), b) Then
    Console.WriteLine("Value entered must be a number")
    GoTo Line98
 End If

如果它可以解析用户的输入,则b将是解析的值,否则b的值仍为0 ...

按评论编辑

Dim b As Integer
Do Until b > 0
    Console.WriteLine("Please input the value of, B:")            
    If Not Integer.TryParse(Console.ReadLine(), b) OrElse b <= 0 Then
      Console.WriteLine("Value entered must be a number and not equal 0")
      GoTo Line98
    End If
 Loop