Revised code for guessing program.

by Solitaire (Login Solitaire1)
S

 
I wanted you to post the code after you revised it. But I see that it's overly complicated and I also see a lot more legacy code.

Here is a new sample you can try out for yourself. Just place one label, one textbox, and one button on your form, in that order. Change the names of the controls to lblGuess, txtGuess, and btnRestart. Change the text of the button to Restart. Then copy and paste the following code to the edit window, replacing anything else that's there:

---------------------------------------------------------------------------

Public Class Form1
Dim randnum As New Random()
Dim secret As Integer

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
secret = randnum.Next(1, 101)
lblGuess.Text = "Enter a number from 1-100:"
End Sub

Private Sub txtGuess_KeyPress(ByVal sender As Object, ByVal _
e As System.Windows.Forms.KeyPressEventArgs) Handles txtGuess.KeyPress
If e.KeyChar = Chr(13) Then
Call Result()
e.Handled = True
End If
End Sub

Sub Result()
Dim guess As Integer
Integer.TryParse(txtGuess.Text, guess)
If guess > secret Then
lblGuess.Text = guess & " is too high.  Try again:"
ElseIf guess < secret Then
lblGuess.Text = guess & " is too low.  Try again:"
Else
lblGuess.Text = "Just Right!"
MessageBox.Show("Well done, you got it!" & _
vbNewLine & "The number was " & secret, "YOU WON")
End If
txtGuess.Clear()
txtGuess.Focus()
End Sub

Private Sub btnRestart_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnRestart.Click
txtGuess.Clear()
txtGuess.Focus()
lblGuess.Text = "Enter a number from 1-100:"
secret = randnum.Next(1, 101)
End Sub

End Class

--------------------------------------------------------------------------
Note: If the statement is too long to display without scrolling, you can use a space and underscore before pressing Enter to continue the statement on the next line. This is called the line continuation character, and the result is considered as a single statement. I did this in the sample above so that it can be copied without an error.

Posted on Mar 12, 2010, 5:51 PM

Respond to this message   

Return to Index

Response TitleAuthor and Date
Thanks solitaireunseenmachine on Mar 12
Here are two more samples:Solitaire on Mar 12

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