| Chapter 3- Data Types and Operators | Boolean Expressions Page 2 3 4 |
| The If Statement Page 2 3 4 5 6 7 8 9 | |
| Arithmetic Operations Page 2 3 4 5 6 | Boolean Operators and Nested If Statements Page 2 3 4 5 6 7 |
| Events and Sequential Processing Page 2 3 4 5 | More Examples Page 2 3 4 5 6 7 8 9 10 11 12 |
| Datatypes and Conversions Page 2 3 4 5 6 7 | Using Check Box and Option Controls Page 2 3 4 5 6 7 8 9 10 |
| Variable Declarations - Local and Global Page 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Exercises Page 2 3 4 5 6 7 8 |
| Chapter 4- Selection Statements | Review Questions |
| Introduction | |
4-6: More on Nested If Statements
Exercise 4-4: Improving the Guessing Game (continued)
Incrementing the Counter
Whenever the user enters a guess and presses the Check It button the guessesRemaining variable must be decreased by one. When the value reaches zero either the game ends with the user having lost, or it ends with the user having won (guessed the correct number on the last guess). The game can also end earlier, if the user guesses the correct number before their last guess.
The click event of the Check It button contains this code. The logic is as follows
decrease the guessesRemaining counter
display (maximum
- counter) in guessesRemaining in the label object
if (counter is greater
than zero) then
if (guess less than correct value)
then
display message stating guess too low
else
if (guess is greater than correct value) then
display
message stating guess too high
else
display
message stating win - guess correct
disable the Check It button
end
if
else
if (guess is correct) then
display message stating win - guess
correct
else
display message stating loss -
guesses exceeded
end if
disable the Check It button
end
if
You wrote the contents of the first block of the outer If statement - i.e. the code to compare the guess to the correct value and display an appropriate message - in Exercise 4-2, which you can reuse here. In the following code use variable names guess for the local variable assigned the value entered by the user in the guess textbox, guessesRemaining, MaxGuesses (yet to be declared or given a value, but we'll deal with that next!), and numToGuess (for the randomly chosen value that is being guessed), and object names txtGuess, btnCheckIt, lblRemaining, lblMessage.