Build a number guessing game
40 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A guessing game is loop practice in disguise: the computer hides a number and the player keeps guessing until they find it.
What you'll build
A number guessing game. The computer picks a secret number from 1 to 100. The player has 7 attempts, and after each guess the program says Too high! or Too low!.
When the round ends, the player can play again with a new number.
Sample run (your numbers will differ)
=== Number Guessing Game === I am thinking of a number from 1 to 100. You have 7 attempts. Your guess: 50 Too high! Your guess: 25 Too low! Your guess: 150 Please guess a number from 1 to 100. Your guess: 37 Too high! Your guess: 35 Correct! Attempts used: 4 Play again? (y/n): n Thanks for playing!
Requirements
Your program should do all of these.
- Pick a random secret number from 1 to 100 for every round.
- When started with a number, like
java GuessingGame 42, use it as the seed ofRandomso the game can be replayed exactly (MentorNxt's hidden tests do this); started without one, pick truly random numbers. - Read guesses with
Scannerand printToo high!,Too low!orCorrect!. - Allow at most 7 attempts. After 7 wrong guesses, print
Out of attempts. The number was 51.(the secret number). - Do not count guesses outside 1 to 100; ask again instead.
- Show how many attempts the player used.
- Ask
Play again? (y/n)and start a new round onyorY.
Build it step by step in the Build tab (5 milestones, each ends with a program that runs). Commit and push after each one: MentorNxt checks every push and shows the result in the Submit tab.
What's next
You finished the preview of Java Basics Mini Projects
Java Programming has 26 sections, 252 modules and 1949 lessons. An account opens every lesson and saves your progress.
Next step
Start building
5 milestones