About Lesson
here’s a possible logic for building the “Guess the Number” game:
- Generate a random number between 1 and 100.
- Prompt the user to enter a guess.
- Read the user’s input from the console.
- Check if the user’s guess is equal to the random number.
- If the user’s guess is correct, print a congratulatory message and end the game.
- If the user’s guess is incorrect, provide feedback by telling the user if the guess is too high or too low.
- Repeat steps 2-6 until the user has used up all of their guesses or correctly guesses the number.
Here is a more detailed algorithm for the logic:
- Generate a random number between 1 and 100.
- Use the
Math.random()
method to generate a random number between 0 and 1. - Multiply this number by 100 to get a random number between 0 and 100.
- Cast this number to an integer to get a random integer between 0 and 100.
- Add 1 to the random integer to get a random number between 1 and 100.
- Assign this random number to a variable called
randomNumber
.
- Use the
- Prompt the user to enter a guess.
- Print a message to the console that asks the user to guess the number.
- Read the user’s input from the console.
- Create a
Scanner
object to read input from the console. - Use the
nextInt()
method of theScanner
class to read an integer from the console. - Assign this integer to a variable called
guess
.
- Create a
- Check if the user’s guess is equal to the random number.
- Use an
if
statement to check ifguess
is equal torandomNumber
. - If
guess
is equal torandomNumber
, set a boolean variable calledhasWon
totrue
and end the game.
- Use an
- If the user’s guess is incorrect, provide feedback by telling the user if the guess is too high or too low.
- Use an
else
statement to provide feedback to the user. - If
guess
is less thanrandomNumber
, print a message that says “Too low!”. - If
guess
is greater thanrandomNumber
, print a message that says “Too high!”.
- Use an
- Repeat steps 2-6 until the user has used up all of their guesses or correctly guesses the number.
- Use a
for
loop to allow the user to guess a maximum of 10 times. - Decrement a counter variable called
guessesLeft
by 1 on each iteration of the loop. - Use a
break
statement to exit the loop if the user correctly guesses the number. - Use an
if
statement to end the game if the user has used up all of their guesses.
- Use a
- Print a message to the console that informs the user if they have won or lost the game.
- Use an
if
statement to check the value of thehasWon
variable. - If
hasWon
istrue
, print a congratulatory message to the console. - If
hasWon
isfalse
, print a message that reveals the random number to the console.
- Use an
Join the conversation