VB.Net InputBox验证负数

VB.Net InputBox validation negative number

我正在开发一个让用户在 InputBox 中输入数字的程序。我可以编写代码来验证输入值是否为数字,但我无法想出一个程序来验证 InputBox 中的负数。

        Dim UserInput As String = ""
        Dim UserInputAsNumber As Integer
        Dim SumofTotal As Integer

        'to display InputBox
        UserInput = (InputBox("Enter a positive number", "Input Needed"))

        'to capture userinput is not numeric value
        While (Not IsNumeric(UserInput))
            UserInput = (InputBox("Enter a positive number", "Input Needed"))
        End While

        'if userinput is number, convert the value to numeric variable
        UserInputAsNumber = CInt(UserInput)

        If (UserInputAsNumber <= 0) Then
            UserInput = (InputBox("Enter a positive number", "Input Needed"))
        Else
            SumofTotal = CInt(((UserInputAsNumber * (UserInputAsNumber + 1)) / 2))
            'calculation
        End If

        MessageBox.Show("The sum is " & CStr(SumofTotal))
    End Sub

您需要遍历代码,直到获得有效的正整数。您可以通过使用 Integer.TryParse 验证字符串并将其转换为整数来简化事情(无效的字符串将转换为零)。

Private Sub btnEnterNumbers_Click(sender As Object, e As EventArgs) Handles btnEnterNumbers.Click
    Dim UserInput As String = ""
    Dim UserInputAsNumber As Integer
    Dim SumofTotal As Integer

    Do While UserInputAsNumber <= 0
        'to display InputBox
        UserInput = (InputBox("Enter a positive integer value", "Input Needed", "10"))

        'convert to integer, will be zero if not valid integer
        Integer.TryParse(UserInput, UserInputAsNumber)
    Loop

    '    Gauss formula to calculate the total of a sequence of numbers from userinput
    SumofTotal = CInt(UserInputAsNumber * (UserInputAsNumber + 1) / 2)

    MessageBox.Show("The sum of the numbers 1 through " & CStr(UserInputAsNumber) & " is " & CStr(SumofTotal))
End Sub