none
one little problem, Random number guessing game

    Question

  • i got it to work, the only issue i am facing is that if i enter a non integer the application takes me to the following line 

      ' Convert the user input string to an integer
                intGuess = CInt(strInput)

    here is the full coding 

    Public Class Form1
        Dim strInput As String            ' Hold the string input
        Dim rand As New Random            ' Declare and create a random number
        Dim intGuess As Integer           ' Hold the number guessed
        Dim intTotal As Integer           ' Hold the total number of guesses
        Dim intCount As Integer           ' Loop Counter
        Dim intRandNum As Integer         ' Hold the random number value
        Private Sub btnGuess_Click(sender As Object, e As EventArgs) Handles btnGuess.Click
            'Assign a random integer in the range of 1 to 100 to the variable intRandNum
            intRandNum = rand.Next(100) + 1

            Do
                strInput = InputBox("Guess a number between 1 and 100.", "Guess the Number")

                If strInput = String.Empty Then
                    MessageBox.Show("Please enter a valid integer between 1 and 100")
                    Exit Do
                End If

                ' Incriment intCount with each guess of the loop
                intCount += 1

                ' Convert the user input string to an integer
                intGuess = CInt(strInput)

                ' Compare the user input against random number and display result

                If intGuess > intRandNum Then
                    lblOutput.Text = ("Too high, try again.")

                ElseIf intGuess < intRandNum Then
                    lblOutput.Text = ("Too low, try again.")

                ElseIf intGuess = intRandNum Then
                    ' If its correct make place intCount into intTotal variable
                    intTotal = intCount
                    lblOutput.Text = ("Great JOB! You Guessed the number in " & intTotal & " attempts")
                End If
            Loop Until intGuess = intRandNum
        End Sub

        Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
            Me.Close()
        End Sub
    End Class

    not sure why i am getting that error, if some one can point out the mistake, i would greatly appreciate it.

    Sunday, March 27, 2016 6:41 PM

Answers

  • Try a different condition:

        If Not IsNumeric(strInput) Then
            MessageBox.Show("Please enter a valid integer between 1 and 100")
            Exit Do
        End If


    But since you need integers only, then use Integer.TryParse and some other tests, to exclude numbers that are not in range.  
    Sunday, March 27, 2016 7:27 PM