Friday, November 19, 2010

How do I keep the same number even after I click the button in VB?

Private Sub btnGuess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuess.Click

Dim guess As Integer

Randomize()

' Generate random value between 1 and 100.

Dim x As Integer = CInt(Int((100 * Rnd()) + 1))



guess = CInt(txtGuess.Text)



If guess = x Then

lblHiOrLow.Text = ';You guessed it!';

Else

If guess %26gt; x Then

lblHiOrLow.Text = ';Guess Lower';

Else

lblHiOrLow.Text = ';Guess Higher';

End If

End If



Static intCount As Integer



intCount = intCount + 1



If intCount = 1 Then

lblNumber.Text = ';You've guessed '; %26amp; intCount %26amp; '; time.';

Else

lblNumber.Text = ';You've guessed '; %26amp; intCount %26amp; '; times.';

End If

End Sub



In other words the number keeps changing so obviously its a little hard to guess. How do I get the number then store it?How do I keep the same number even after I click the button in VB?
You need two things, a global variable to store the guess and a global variable to store the state of the program.



You then need to initialize a value at the beginning of the process by running the random number generator, then only resetting the value the time after you have guessed it. You can do this by setting and checking the state variable. If it is the firstGuess, then you will set the value, otherwise you will use the old value.



Once you have found the correct value, then set the state back to firstGuess so that the next time a new value is generated.



You will also need to do the proper accounting for intCount.



Private Sub btnGuess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuess.Click





Static guess as Integer

Static firstGuess as Boolean = True



Randomize()

If( firstGuess ) Then

' Generate random value between 1 and 100.

Dim x As Integer = CInt(Int((100 * Rnd()) + 1))



guess = CInt(txtGuess.Text)

firstGuess = False

End If



If guess = x Then

lblHiOrLow.Text = ';You guessed it!';

firstGuess = True

Else

If guess %26gt; x Then

lblHiOrLow.Text = ';Guess Lower';

Else

lblHiOrLow.Text = ';Guess Higher';

End If

End If



Static intCount As Integer



intCount = intCount + 1



If intCount = 1 Then

lblNumber.Text = ';You've guessed '; %26amp; intCount %26amp; '; time.';

Else

lblNumber.Text = ';You've guessed '; %26amp; intCount %26amp; '; times.';

End If

End Sub

No comments:

Post a Comment