Write a guess a number game where the program creates a secret number (integer of course) and the user has to guess it
This is how you make a random number between 1 and 100: int secret = (int) (Math.random() * 100) +1;
When the user enteres a guess, say if it is too high, too low or just right.
Print out the number of guesses once the user wins.
This will be marked more carefully for formatting, variable names, etc.
In this program, you're going to have to keep asking for the next guess until they get it right. This means that we need to use a loop in our program
There are two types of loops: for loops and while loops. Some languages have a couple of variations on the while loop (e.g. until, do while).
while (condition) {
...
...
}
As long as whatever is in the red box is TRUE, then the loop will keep looping and do everyhing that is in the { } over and over again.
1 | 2 | 3 |
---|---|---|
while (true) {
get the next guess
check to see if it's correct
print "too high", etc
...
} |
while (guess != secret) {
get the next guess
check to see if it's correct
print "too high", etc
...
} |
do {
get the next guess
check to see if it's correct
print "too high", etc
...
} while (secret != guess); |
Since this loop loops forever, then how do we ever end the game if the user guesses the correct number? | How can we check what guess is at the top of the loop when the user only starts guessing inside the loop? | This is a do-while loop It is like the previous example, except that it is always guaranteed to execute at least once (the condition to be checked is at the bottom). |
Solution: We use the break; command.So your "if" statement would say something like this: "if the guess == secret then break;" |
Solution:Before we start the loop, we need to set "guess" to some number that the secret number will never be.int guess = -1;
while(guess != secret) {
...
|
Note that in the do-while format, you MUST end the last line with a ; (semicolon).
Remember: all lines must end in { } or ;
READ THIS! you should never use System.exit(0) unless you have a very specific and good reason to do so. It is not good programming technique and should be avoided.
"break" or "return" are the correct ways to exit a loop