Learn Java Basics
About Lesson

here’s a possible logic for building the “Guess the Number” game:

  1. Generate a random number between 1 and 100.
  2. Prompt the user to enter a guess.
  3. Read the user’s input from the console.
  4. Check if the user’s guess is equal to the random number.
  5. If the user’s guess is correct, print a congratulatory message and end the game.
  6. If the user’s guess is incorrect, provide feedback by telling the user if the guess is too high or too low.
  7. 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:

  1. 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.
  2. Prompt the user to enter a guess.
    • Print a message to the console that asks the user to guess the number.
  3. Read the user’s input from the console.
    • Create a Scanner object to read input from the console.
    • Use the nextInt() method of the Scanner class to read an integer from the console.
    • Assign this integer to a variable called guess.
  4. Check if the user’s guess is equal to the random number.
    • Use an if statement to check if guess is equal to randomNumber.
    • If guess is equal to randomNumber, set a boolean variable called hasWon to true and end the game.
  5. 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 than randomNumber, print a message that says “Too low!”.
    • If guess is greater than randomNumber, print a message that says “Too high!”.
  6. 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.
  7. 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 the hasWon variable.
    • If hasWon is true, print a congratulatory message to the console.
    • If hasWon is false, print a message that reveals the random number to the console.
Join the conversation