Problem:
Write a program in visual basic 6 that will ask the user to enter a number from 1 to 10. The program will also generate a random number from 1 to 10, the program will then compare the user input and the generated number, the program must display a message if the user had guessed the number or not.
Solution:
We are going to use Rnd (random) function for the program to randomly generate number from 1 to 10. We will also validate the user input, the user must not leave the field empty and the user must be prompted to enter only numbers from 1 to 10.
Let the coding begin
- Open your visual basic 6 program and select Standard EXE.
- We will be adding the following objects to our form.
- 3 labels
- 1 textbox
- 1 command button
- This is how we design the form (you are free to design your own)
- On the keypress event of the textbox, place the code below
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = 46 Or KeyAscii = vbKeyBack Then
Else
Beep
KeyAscii = 0
End If
Code explanation:
This will prevent the user to enter a non-numeric value to the textbox.
- To proceed to the keypress event, view the code of the form then select Text1 from the 1st combo box and select keypress from the 2nd combo box.
The image below may guide you.
- Double click the Check your guess button and paste the code below
If Text1.Text = "" Or Val(Text1.Text) > 10 Then
MsgBox "Please enter a number from 1 to 10"
Else
Label3.Caption = Int(Rnd * 11)
End If
Code Explanation:
This will validate first the input of the user, a message will be displayed if the user has forgot to enter a number or the user has enter a number not ranging from 1 to 10. If the user enters a right value then it will randomly generate a number from 1 to 10 and display it in Label3.
- Double click the Label3 or the label with the caption (-). Kindly refer to the form above.
Paste the code:
If Val(Label3.Caption) = Val(Text1.Text) Then
MsgBox "correct"
Else
MsgBox "incorrect"
End If
Code Explanation:
It will match the value from the user input and the generated number, if it matches then a message box with message correct will be displayed else incorrect it does not match.
- Test the project by pressing F5.
- Don’t forget to save.
We will convert this to C#, VB.net and other programming languages.