VB.Net InputBox验证负数

时间:2015-04-23 02:10:28

标签: vb.net validation negative-number inputbox

我正在为一个用户在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

1 个答案:

答案 0 :(得分:1)

您需要遍历代码,直到获得有效的正整数。您可以通过使用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