Skip to content
Tutorials Center
My learning

Topics

Lesson 172 of 201 ยท Projects

Project: Number Guessing Game

Build a number guessing game in Java step by step - Random with a seed, an input loop, hints, attempt limits, difficulty levels, replays and a computer that guesses.

The number guessing game is the classic first project: the computer picks a secret number, you guess, and it answers "too low" or "too high" until you find it. It looks tiny, but a good version touches almost every beginner topic at once: random numbers, loops, input that might be garbage, methods that return results, enums, a class that holds game state, and a session that keeps statistics across games.

You'll build it in five stages. Every stage is a complete, runnable program, and the Input box under each one holds the "keyboard input" for the run, one line per guess. Change those lines and run again to play a different game. The finished program even turns the tables: in the last stage, you think of a number and the computer finds it in at most seven questions.

The project practices random numbers, reading input, while loops, enums, switch expressions, classes and exceptions. After this, the Grade Book project is a good next step.

The rules and the plan

Here is the game we're aiming for:

  • The computer picks a secret whole number in a range, for example 1 to 100.
  • The player guesses. After each guess the computer says whether the secret is higher or lower, and narrows down the possible range.
  • Text that isn't a number, or a number outside the range, is rejected and doesn't cost an attempt.
  • There's a limit on attempts. When it runs out, the computer reveals the secret.
  • After each game the player can play again, and the program tracks wins and the best score.

A good habit is to split a program like this into logic (comparing a guess with the secret, counting attempts) and input/output (reading lines, printing messages). Logic that doesn't read or print is easy to test and easy to reuse, which you'll see pay off in Stage 5.

Stage 1: comparing a guess

Start with the heart of the game: given a guess and the secret, what's the answer? There are exactly three possible answers, so they are an enum, not strings or magic numbers like -1, 0 and 1.

Java Stage 1: the three possible answers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two small design choices are worth noticing:

  • check decides, describe talks. The comparison returns a Hint value and knows nothing about wording. If you later translate the game or build a window for it, check stays the same.
  • The switch expression has no default. It covers all three constants, so the compiler knows it's complete. Add a fourth constant such as CLOSE and the code stops compiling until you handle it, which is exactly the safety you want (see Switch).

Stage 2: a secret number and a guessing loop

Now the computer picks the secret with java.util.Random. The call random.nextInt(1, 101) returns a number from 1 up to but not including 101, so 1 to 100. Forgetting that the upper bound is exclusive is the most common bug in this project: write nextInt(1, 100) and the number 100 can never be the secret.

The Random is created with a seed, new Random(7). A seeded generator produces the same sequence every run, which is perfect while you build and test: the secret is always 37, so the guesses in the Input box always play out the same way. Remove the seed (new Random()) to get a different secret each run. Random Numbers explains seeds in depth.

The loop reads one line per guess. Each line is checked in two steps: is it a number at all, and is it inside the range? Only valid guesses count as attempts.

Java Stage 2: the game loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output ends with Correct! You needed 4 attempts. Six lines were read, but forty and 0 were rejected with continue, which jumps back to the top of the loop before attempts++ runs.

Notice the hasNextLine() check at the top of the loop. On your own computer the program would simply wait for the next line. Here, all the input is known in advance, and calling nextLine() after the last line would throw NoSuchElementException. Checking first turns "the player gave up" into a normal ending. Delete the last line of the Input box and run again to see it.

while (true) with return is fine for a small main. Once the loop sits inside a method that must do more work afterwards, use break, or better, a condition like while (!game.isOver()), which is where Stage 3 goes.

Stage 3: a Game class, difficulty levels and an attempt limit

main is getting crowded: it holds the secret, the counter, the range and all the printing. Time to give the game its own class. A Game object owns the secret and the attempt counter as private fields, so nothing outside can peek at the secret or reset the counter. That's encapsulation doing real work in a game about secrets.

Difficulty becomes an enum whose constants carry data: the largest number and the number of attempts allowed. How many attempts are fair? With the best strategy, each guess halves the range of possible numbers. Halving 100 numbers takes 7 steps to get down to one (2โท = 128 โ‰ฅ 100), and 1,000 numbers take 10 (2ยนโฐ = 1,024). The limits below give exactly that on normal and hard, so a player who thinks clearly always wins, and one extra attempt on easy.

The game also keeps track of the known range. After "too low" on 500 the secret must be above 500, so the hint says so, and a guess outside the known range gets a gentle warning. It still counts: it was a real attempt, just a wasted one.

The first input line now chooses the game: a difficulty, optionally followed by a seed. hard 2026 plays a reproducible hard game; hard alone uses a new random secret.

Java Stage 3: a Game class with difficulty and limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The secret with seed 2026 is 800. The guess of 600 after "too low on 750" is flagged as wasted, and the player still wins on the ninth attempt, one before the limit. Try removing the 600 line: the same strategy then wins in eight.

The details that make this class trustworthy:

  • The constructor takes a RandomGenerator, not a seed. RandomGenerator is the interface that Random, SplittableRandom and the newer algorithms all implement. The game doesn't care where its numbers come from; main decides. In a unit test you could even pass a generator that always returns 42. Passing in what a class needs, instead of letting it create it, is called dependency injection, and it is the reason this class is easy to test (see Unit Testing).
  • Bad guesses are exceptions, not counted attempts. guess throws IllegalArgumentException before attempts++, so out-of-range numbers are free. main catches NumberFormatException first: it's a subclass of IllegalArgumentException, so the order of the catch blocks matters (the more specific one must come first, or the code doesn't compile).
  • secret() refuses to answer during a game. A getter that leaks the secret would make cheating a one-liner, so it throws IllegalStateException until the game is over.
  • toUpperCase(Locale.ROOT) turns hard into HARD for Difficulty.valueOf. Plain toUpperCase() uses the computer's language settings, and in Turkish the letter i becomes a dotted ฤฐ, so a name containing i would no longer match its enum constant. Locale.ROOT gives the same result everywhere, which is what you want for program-internal text like commands and keys.

An unknown difficulty such as extreme makes valueOf throw and the program stops with a stack trace. That's acceptable for a first version; the next stage handles it properly.

Stage 4: play again, with statistics

A real game session has several rounds. This stage wraps a game in a loop, asks "Play again?" after each one, and keeps statistics: games played, games won, the best (fewest) attempts in a win and the average attempts per win.

The statistics get their own small class, so main doesn't juggle four counters. The settings line is now validated: an unknown difficulty prints the valid choices and falls back to NORMAL instead of crashing.

There's one more subtle decision. With a seed, the program creates one Random for the whole session and passes it to every game. Each game takes the next number from the same sequence, so the games differ from each other, yet the whole session is still reproducible. Creating new Random(seed) inside the loop would give every game the same secret.

Java Stage 4: several games and a scoreboard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With seed 42 the three secrets are 11, 4 and 9. The second game is lost on purpose (counting down from 20 is not a strategy), so the report says 3 played, 2 won (67%), best 2 attempts and an average win of 3.0 attempts.

A few things to try:

  • Change easy 42 to medium 42 and watch the fallback message.
  • Remove the final no. askYesNo then sees the end of input and returns false, so the session ends cleanly either way.
  • Change the final no to y. The fourth game starts, finds no input and is abandoned: it's neither won nor lost, and Stats.record ignores it instead of counting it as a loss.

100.0 * won / played uses a double literal on purpose. With 100 * won / played the division happens on integers and 2 out of 3 becomes 66, not 66.7. The %.0f format then rounds the double to 67.

Stage 5: turning the tables

Now you think of a number and the computer guesses. You answer each guess with higher, lower or yes (or just h, l, y). The computer uses binary search: it always guesses the middle of the range that is still possible, so each answer throws away half of the candidates. That's why 7 questions always suffice for 1 to 100, the same number you used as the normal attempt limit. Searching and Sorting covers binary search as an algorithm on arrays.

The computer also catches cheating. If your answers contradict each other (you said "higher" than 60 and later "lower" than 61), the range becomes empty and no number fits.

Java Stage 5: the computer guesses your number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The secret here was 69: the computer asked 50, 75, 62, 68, 71 and 69, closing in from both sides. Change the input to describe your own number, or try lying: answer h, h, h, l, l, l (one per line). After "higher than 88" and "lower than 89", nothing is left, and the program says so.

Why low + (high - low) / 2 instead of (low + high) / 2? For 1 to 100 both are fine. But when low and high are both above about one billion, low + high exceeds Integer.MAX_VALUE and wraps around to a negative number. This exact bug sat unnoticed in the JDK's own binary search for years, so it's worth writing the safe version by habit.

Ideas to extend it

  • Warmer and colder. Instead of "too low", tell the player whether this guess is closer to the secret than the previous one. You'll need to remember the last guess in Game.
  • A high-score file. Save the best score per difficulty with Files.writeString and load it at start (see Files). On your own computer it survives between runs.
  • Hint tokens. Give the player one hint per game, ?, that reveals whether the secret is even or odd, at the cost of an attempt.
  • Computer versus computer. Let the Stage 5 binary search play against the Stage 3 Game class directly, for every secret from 1 to 1,000, and print the worst case. It should never exceed 10.
  • Unit tests. Write JUnit tests for Game using a RandomGenerator that returns a fixed value (see Unit Testing).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What range of values can new Random().nextInt(1, 100) return?

    The lower bound is inclusive and the upper bound is exclusive, so 100 is never returned. For 1 to 100 you need nextInt(1, 101).
  2. 2. In Stage 2, why don't the lines forty and 0 count as attempts?

    Both checks end with continue, which skips the rest of the loop body, including the attempts++ line.
  3. 3. A program creates new Random(42) inside the replay loop, once per game. What happens?

    A fresh generator with the same seed restarts the same sequence, so the first nextInt is the same every time. Create the generator once and share it.
  4. 4. Why must catch (NumberFormatException e) come before catch (IllegalArgumentException e)?

    A catch for a superclass also catches its subclasses. Putting it first would make the subclass catch unreachable, which is a compile error.
  5. 5. Using binary search on the range 1 to 1000, what is the most guesses the computer can need?

    Each answer halves the remaining range, and 2 to the power of 10 is 1,024, which covers 1,000 numbers.

Summary

  • Split the game into logic (check, Game) and input/output (main); the logic returns values like the Hint enum and never prints.
  • Random.nextInt(origin, bound) excludes the bound. A seed makes a run reproducible; create the generator once and share it.
  • Read input with hasNextLine() before nextLine(), reject non-numbers and out-of-range values with continue or exceptions, and count only valid attempts.
  • A Game class keeps the secret and counters private, takes a RandomGenerator from outside (dependency injection), and refuses to reveal the secret early.
  • A replay loop with a Stats class turns single games into a session; integer division needs a double for percentages.
  • Binary search finds any number from 1 to 100 in at most 7 guesses; compute the middle as low + (high - low) / 2.

Next: Project: Grade Book, where you'll read a whole class's scores, compute averages and letter grades, and print a formatted report.