And’s and Or’s
Using OR’s with If Statements
Fixing the Problem with the Hint
Private
Sub cmdhint_Click()
'tells
user if he is closer or farther away than 30 from the secret number
Dim
difference As Integer
difference
= guess - secretnumber 'calculates how
far the guess is off
Adding OR difference < -30 allows the computer to
say that “You’re Cold” as long as one of the comparisons are true
If
difference > 30 Or difference < -30 Then
lblmessage.Caption = "You're so cold
you are freezing"
Else
lblmessage.Caption = "You're getting
warmer"
End
If
End
Sub
With
an OR statement, only one part of the if Statement Need to be True
With an And placed in an If statement both sides of the statement must be true….
Add a variable called cheater to the form level variables as follows
Dim secretnumber As Integer
Dim guess As Integer
Dim cheater As Boolean
Step 1 Give cheater an original value
In the form load event…. Assign cheater a value of false and if you haven’t typed Randomize Timer. Do it so the secret numbers will be different all the time
Private Sub Form_Load()
'sets the values of the initial variables
Randomize Timer
cheater = False
End Sub
Step 2 Make
the value of cheater change when the “I give up button is pressed”
Private Sub cmdgiveup_Click()
'reveals secret number
txtdisplay = secretnumber
cheater = True 'changes the value of cheater
End Sub
Step
3. Change the winning if statement to
detect if you cheated.
Private
Sub txtguess_KeyPress(KeyAscii As Integer)
'
checks if answer is correct after enter key is hit.
If
KeyAscii = 13 Then 'if i hit the enter
key
guess = txtguess.Text 'loads user guess into variable guess
If guess > secretnumber Then
lblmessage.Caption = "Too High"
If guess < secretnumber Then
lblmessage.Caption = "Too Low"
If guess = secretnumber
And cheater = False Then
If
guess = secretnumber And cheater = True Then
lblmessage.Caption = "Doesn't really count if you cheat"
End
If
Step
4. If we want to play again we are
going to have to change the value of cheater when we generate another number
Private
Sub cmdsecret_Click()
'generates
a secret number between 0 and 100
cheater = False
secretnumber
= Int(Rnd(1) * 101 + 0)
So in conclusion….. With an And both sides of the comparison must be true but with an OR only one side has to be true.