【问题标题】:input validation in vb 2013 input box string conversion errorvb 2013输入框字符串转换错误中的输入验证
【发布时间】:2016-03-20 18:04:56
【问题描述】:

当我在输入框中输入字母字符或将输入框留空时,我的程序崩溃了。为什么我的验证 if 语句不起作用?

Option Strict On
Public Class frmPickUpSticks
Dim playersTurn As Boolean = False
Dim remainingSticks As Integer 'count sticks
Dim losses As Integer = 0 'count player losses
Private Sub btnNewGame_Click(sender As Object, e As EventArgs) Handles btnNewGame.Click
    lblOutput.Text = ""
    remainingSticks = CInt(InputBox("How many matchsticks would you like (5 - 25)?", "Pick Number of Matches!"))
    'Validate input
    If IsNumeric(remainingSticks) Then
        If (remainingSticks >= 5) And (remainingSticks <= 25) Then
            DisplayMatches()
            If (remainingSticks Mod 4 = 1) Then
                MessageBox.Show("You go first!")
                playersTurn = True
                turns()
            Else
                MessageBox.Show("I go first.")
                turns()
            End If
        Else
        MessageBox.Show("Please enter a number between 5 and 25.")
    End If
Else
    MessageBox.Show("Input must be numeric.", "Input Error")
End If

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    您不能自动获取用户在 InputBox 中键入的内容并将此输入传递给任何需要输入数字的函数或方法。 InputBox 方法被设计为返回一个字符串,这个字符串需要被转换,但你需要使用知道如何解析字符串的方法。否则,未设计用于处理非数字值 (CInt) 的方法将导致异常。

    相反,您应该尝试某种解析,NET 库提供了许多工具供您使用。在您的情况下,正确的是Int32.TryParse

    Dim remainingSticks As Integer
    Dim userInput = InputBox("How many matchsticks .....")
    If Int32.TryParse(userInput, remainingSticks) Then
       .... ok your remainingStick contains the converted value
    Else
       MessageBox.Show("You should type a valid integer number between 5-25")
    

    Int32.TryParse 将查看您的输入字符串并尝试转换为有效的整数值。如果成功,则第二个参数包含转换后的整数并返回 True,如果失败则返回 false,您的第二个参数将具有默认值零。

    当然,在成功转换为整数后,您不再需要使用 IsNumeric 进行检查

    【讨论】:

    【解决方案2】:

    您应该在输入框中使用字符串变量

    dim st as string

    st = InputBox("你想要多少根火柴 (5 - 25)?", "挑选火柴数!"))

    剩余的棍子 = val(st)

    。 . .

    【讨论】:

    • Val 如果数字太大而无法转换为整数,则会抛出异常。此外,是时候忘记 2016 年仍然存在的所有 VB6 兼容性功能了
    • lol@forget vb6 兼容性。 . .我无法自拔,我来自 POWERBASIC 时代,,,,
    猜你喜欢
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 2014-03-25
    • 2016-06-12
    • 2012-05-10
    • 1970-01-01
    相关资源
    最近更新 更多