Here are two more samples:

by Solitaire (Login Solitaire1)
S

 
This is a lot shorter. It makes use of the InputBox and a Do loop to repeat inside a single event until the user guesses the right number. Just place a single button on your form and name it btnGuess. Then copy and paste the following code in the edit window:


Public Class Form1

Private Sub btnGuess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuess.Click
Dim guess, count As Integer, sgess As String
Dim randnum As New Random()
Dim secret As Integer = randnum.Next(1, 101)
sgess = InputBox("Enter a number from 1-100")
count = 0
Do
count += 1
Integer.TryParse(sgess, guess)
If guess > secret Then
sgess = InputBox(guess & " is too high. Try again")
ElseIf guess < secret Then
sgess = InputBox(guess & " is too low. Try again")
Else
MessageBox.Show("Just right! " " You got the number in " & count & " tries.", "The number was " & secret)
End If
Loop Until guess = secret
End Sub

End Class

=============================================================================

This next one is even better. It only counts the tries if user enters a number and displays the count number with each repeat. If nothing is entered, it keeps the last valid guess. It also allows user to stop if a "0" is entered, and shows the random number at the end even if the user stopped before getting the guess right.

=============================================================================

Public Class Form1

Private Sub btnGuess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuess.Click
Dim sgess As String, good As String = "", guess, oldguess As Integer, count As Integer = 0
Dim randnum As New Random()
Dim secret As Integer = randnum.Next(1, 101)
sgess = InputBox("Enter a number from 1-100, 0 to stop after try.")
Do
oldguess = guess
Integer.TryParse(sgess, guess)
If guess <> 0 Then count += 1
If guess = 0 Then guess = oldguess
If guess > secret Then
sgess = InputBox(guess & " is too high. Try again.", "Try #" & count)
ElseIf guess < secret Then
sgess = InputBox(guess & " is too low. Try again.", "Try #" & count)
Else
good = "Just right! You got the number in " & count & " tries."
End If
Loop Until guess = secret Or sgess = "0" 'stop without guessing
MessageBox.Show(good, "The number was " & secret)
End Sub

End Class



    
This message has been edited by Solitaire1 on Mar 13, 2010 11:02 AM
This message has been edited by Solitaire1 on Mar 13, 2010 11:01 AM
This message has been edited by Solitaire1 on Mar 13, 2010 10:48 AM

Posted on Mar 12, 2010, 6:25 PM

Respond to this message   

Return to Index

 Copyright © 1999-2014 Network54. All rights reserved.   Terms of Use   Privacy Statement