Skip to lesson
MentorNxt home

Java Programming

Java Basics Mini Projects

Build a number guessing game

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.

  1. Pick a random secret number from 1 to 100 for every round.
  2. When started with a number, like java GuessingGame 42, use it as the seed of Random so the game can be replayed exactly (MentorNxt's hidden tests do this); started without one, pick truly random numbers.
  3. Read guesses with Scanner and print Too high!, Too low! or Correct!.
  4. Allow at most 7 attempts. After 7 wrong guesses, print Out of attempts. The number was 51. (the secret number).
  5. Do not count guesses outside 1 to 100; ask again instead.
  6. Show how many attempts the player used.
  7. Ask Play again? (y/n) and start a new round on y or Y.
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