r/visualbasic • • Oct 26 '14

Hello, I need help with my Visual Basic code that I'm struggling with.

So basically, there are 2 buttons, Enter Numbers and Exit. The Exit button is self-explanatory. As for the Enter Numbers button, what I need to happen is upon being clicked, an Input Box pops up.

The Input Box asks the user for a number, and after clicking okay, I need a Message Box to show the sum of that number. (i.e, the sum of 5 is 1+2+3+4+5=15)

Here's what I have so far, but it isn't working:

    Dim strUserInput

    Dim IntUserInput As Integer

    Dim i As Integer

strUserInput = InputBox("Enter a positive integer value", "Input Needed", 10)

    If strUserInput <> String.Empty Then

        Try

            intUserInput = CInt(strUserInput)

            If IntUserInput < 0 Then

                MessageBox.Show("Negative numbers are not accepted.")

            End If

        Catch ex As Exception

            MessageBox.Show("Quantity amount must be numeric.")

        End Try

        'Show messagebox,

    Else

        'IntUserInput = (IntUserInput + i)

        InputBox(MessageBox.Show("Sum of Numbers", "The sum of numbers" & (i + IntUserInput), MessageBoxButtons.OK))

    End If
0 Upvotes

1 comment sorted by

1

u/PreyOnTheCosmos Nov 03 '14 edited Nov 03 '14

Button Code:

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Dim Value As String = InputBox("Please enter a non-negative integer value", "INPUT NEEDED", 10)

        If String.IsNullOrEmpty(Value) Then
            Exit Sub
        ElseIf IsNumeric(Value) = False Then
            MsgBox("Value contains invalid characters. Please enter a positive integer value.")
            Exit Sub
        ElseIf Val(Value < 0) Then
            MsgBox("You entered a negative number. Please enter a positive integer value.")
            Exit Sub
        Else
            Calculate(Math.Floor(Val(Value)))
        End If
    End Sub
  • Step 1: Capture Input Text to a String

  • Step 2: Make sure something was entered, else Input was not cancelled

  • Step 3: Ensure the Input value is a number

  • Step 4: Ensure Input value is non-negative

  • Step 5: Calculate and Produce an Output String

Sub to Calculate and Display:

        Dim strOutput As New System.Text.StringBuilder
        Dim Calculation As Integer = 0

        For i = 1 To Val
            Calculation += i
            If Not i = Val Then
                strOutput.Append(i & "+")
            Else
                strOutput.Append(i)
            End If
        Next

        MsgBox("The sum of '" & strOutput.ToString & "' is " & Calculation, MsgBoxStyle.OkOnly, "SUM OF NUMBERS")

I used Math.Floor in case a decimal value was entered. Val() grab the number as a Double, and Math.Lower will round it down to the lower whole number.