【问题标题】:Validation to ensure value entered is a integer验证以确保输入的值是整数
【发布时间】:2019-03-28 05:46:48
【问题描述】:

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

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”任何非数字数据,我会收到错误 Unhandled Exception: System.InvalidCastException: Conversion from string “gakjdg” to type 'Integer' is not valid.

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

 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")

【问题讨论】:

  • If Not Integer.TryParse(b, New Integer) Then.... 这是一个快速的解决方案,适合您的需求。请see 更多关于TryParse...
  • @Çöđěxěŕ,但是我试过了,我输入 f 让我们说,我得到错误 Unhandled Exception: System.InvalidCastException: 从字符串“f”到类型“整数”的转换无效跨度>

标签: vb.net validation


【解决方案1】:

查看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

【讨论】:

  • @codexer 再问一个问题,如果 (a = 0) Then Console.WriteLine("Error, number can not be 0, Please Try Again!") GoTo line93 '这将要求输入 A再次,并重复该过程,直到 a 不是 0 End If If Not Integer.TryParse(Console.ReadLine(), a) Then Console.WriteLine(vbLf & "Error: Value entered must be a number") GoTo line93 End If,我将如何结合这两个
  • @loco3424 与该声明相比,a/b 可以小于 0。在您的帖子中,您说数字可能是负数...此外,如果您还有其他问题,请与原件分开提问。此外,如果这有帮助,请投票并接受这是否解决了您的问题,以便其他人知道这有效。
  • @codexer,是的,对不起,a 不能是负数,但是如果我输入一个有效数字,它会告诉我输入的值必须是一个数字并且大于 0,然后继续,请帮助
  • 我很困惑,看来你一直在改变你的要求。当前代码将确保用户输入有效数字并确保该数字大于 0,否则将再次循环...
  • @codexer,是的,但是在继续之前它告诉我输入的值必须是一个数字并且大于 0 然后继续,尽管我输入了 9
猜你喜欢
  • 1970-01-01
  • 2021-12-28
  • 2010-11-28
  • 2010-10-15
  • 1970-01-01
  • 2013-05-31
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
相关资源
最近更新 更多