Java Number Guess Game
A Java number guess game picks a secret number and lets the player guess it, answering "higher" or "lower" after each try. It is a perfect second project because it combines random numbers, loops, conditions, input validation and enums in one small program. Along the way you also learn a real algorithm: binary search, the fastest way to find the number.
This project continues from the Java Calculator App and reuses its read-validate-repeat loop. You start by generating a secret number and finish with number-guess-game.jar, a game with three difficulty levels, limited attempts, best scores and a --seed option for repeatable testing. All examples were run on JDK 21.
Generate the Secret Number in Java
The game needs a random whole number in a fixed range, such as 1 to 100. Java offers several generators, covered in detail in Java Random Numbers.
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class SecretNumber {
public static void main(String[] args) {
// a seeded Random gives the same numbers every run (good for testing)
Random seeded = new Random(42);
System.out.print("Seeded Random(42): ");
for (int i = 0; i < 5; i++) {
System.out.print(seeded.nextInt(1, 101) + " ");
}
System.out.println();
// an unseeded generator gives different numbers every run
int secret = ThreadLocalRandom.current().nextInt(1, 101);
System.out.println("Secret is between 1 and 100: " + (secret >= 1 && secret <= 100));
// the old formula with Math.random()
int oldStyle = (int) (Math.random() * 100) + 1;
System.out.println("Math.random() style in range: " + (oldStyle >= 1 && oldStyle <= 100));
}
}
Seeded Random(42): 31 64 49 85 71
Secret is between 1 and 100: true
Math.random() style in range: true
| Way to get 1-100 | Repeatable? | Notes |
|---|---|---|
new Random(seed).nextInt(1, 101) | Yes, same seed gives same numbers | Use for tests and demos |
ThreadLocalRandom.current().nextInt(1, 101) | No | Fast, good default for games |
RandomGenerator.getDefault().nextInt(1, 101) | No | Modern interface (Java 17+) |
(int) (Math.random() * 100) + 1 | No | Older style, easy to get the range wrong |
How it works:
nextInt(1, 101)returns a number from 1 up to but not including 101, so 100 is the largest possible value.- A seed is the starting value of the generator.
new Random(42)produces 31, 64, 49, 85, 71 on every computer, every time. The final game uses this to make test sessions repeatable. Math.random()returns adoublefrom 0.0 to just below 1.0. Multiplying by 100, casting tointand adding 1 gives 1 to 100.
Compare a Guess With Higher or Lower Hints
Each guess has exactly three outcomes, so an enum describes them clearly. A method compares the guess to the secret and returns the hint.
public class CompareGuess {
enum Hint { TOO_LOW, TOO_HIGH, CORRECT }
static Hint check(int guess, int secret) {
if (guess < secret) return Hint.TOO_LOW;
if (guess > secret) return Hint.TOO_HIGH;
return Hint.CORRECT;
}
public static void main(String[] args) {
int secret = 64;
int[] guesses = {50, 75, 62, 68, 64};
int attempts = 0;
for (int guess : guesses) {
attempts++;
Hint hint = check(guess, secret);
String message = switch (hint) {
case TOO_LOW -> "Too low";
case TOO_HIGH -> "Too high";
case CORRECT -> "Correct!";
};
System.out.println("Guess " + attempts + ": " + guess + " -> " + message);
if (hint == Hint.CORRECT) {
System.out.println("Found it in " + attempts + " attempts.");
break;
}
}
}
}
Guess 1: 50 -> Too low
Guess 2: 75 -> Too high
Guess 3: 62 -> Too low
Guess 4: 68 -> Too high
Guess 5: 64 -> Correct!
Found it in 5 attempts.
How it works:
checkcontains only the comparison logic. It does not print anything, which keeps it easy to reuse and test.- The switch expression covers all three enum constants, so no
defaultis needed. If you add a fourth constant later, the compiler reports the missing case. breakends the loop as soon as the guess is correct. The fixed array of guesses stands in for a player while you develop the logic.
Read Guesses Safely With Scanner
Real players type mistakes: words, decimals, numbers outside the range. A helper method keeps asking until it gets a valid whole number, the same pattern as in the calculator project and the Java While Loop lesson.
import java.util.Scanner;
public class ReadGuess {
static final int MIN = 1;
static final int MAX = 100;
// keeps asking until the user types a whole number inside the range
static int readGuess(Scanner scanner) {
while (true) {
System.out.print("Your guess (" + MIN + "-" + MAX + "): ");
String text = scanner.nextLine().strip();
try {
int value = Integer.parseInt(text);
if (value < MIN || value > MAX) {
System.out.println(" Please stay between " + MIN + " and " + MAX + ".");
continue;
}
return value;
} catch (NumberFormatException e) {
System.out.println(" '" + text + "' is not a whole number.");
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int guess = readGuess(scanner);
System.out.println("You guessed " + guess);
}
}
Your guess (1-100): fifty
'fifty' is not a whole number.
Your guess (1-100): 150
Please stay between 1 and 100.
Your guess (1-100): 42.5
'42.5' is not a whole number.
Your guess (1-100): 42
You guessed 42
How it works:
Integer.parseIntthrowsNumberFormatExceptionforfiftyand42.5, because neither is a whole number. Thecatchprints a message and the loop repeats.150parses fine but fails the range check.continuejumps back to the top of the loop and asks again.- Only a valid value reaches
return, so the code that callsreadGuessnever has to check the input again.
Note: Reading the whole line with
nextLine()and parsing it yourself is safer thannextInt(). WithnextInt(), a word likefiftystays in the input buffer and causes an endless loop of errors.
Limit Attempts With Difficulty Levels
A game without a limit is never lost. An enum stores each difficulty level together with its range and its number of attempts.
public class LimitedAttempts {
enum Difficulty {
EASY(50, 10), MEDIUM(100, 7), HARD(1000, 10);
final int maxNumber;
final int maxAttempts;
Difficulty(int maxNumber, int maxAttempts) {
this.maxNumber = maxNumber;
this.maxAttempts = maxAttempts;
}
}
static boolean play(Difficulty level, int secret, int[] guesses) {
System.out.println(level + ": 1-" + level.maxNumber + ", " + level.maxAttempts + " attempts");
int attemptsLeft = level.maxAttempts;
for (int guess : guesses) {
if (attemptsLeft == 0) break;
attemptsLeft--;
if (guess == secret) {
System.out.println(" " + guess + " is correct! Attempts left: " + attemptsLeft);
return true;
}
String direction = guess < secret ? "higher" : "lower";
System.out.println(" " + guess + " -> go " + direction + " (" + attemptsLeft + " left)");
}
System.out.println(" Out of attempts. The number was " + secret);
return false;
}
public static void main(String[] args) {
play(Difficulty.MEDIUM, 37, new int[] {50, 25, 37});
play(Difficulty.MEDIUM, 91, new int[] {10, 20, 30, 40, 50, 60, 70, 80});
}
}
MEDIUM: 1-100, 7 attempts
50 -> go lower (6 left)
25 -> go higher (5 left)
37 is correct! Attempts left: 4
MEDIUM: 1-100, 7 attempts
10 -> go higher (6 left)
20 -> go higher (5 left)
30 -> go higher (4 left)
40 -> go higher (3 left)
50 -> go higher (2 left)
60 -> go higher (1 left)
70 -> go higher (0 left)
Out of attempts. The number was 91
| Level | Range | Attempts | Guesses a perfect player needs |
|---|---|---|---|
EASY | 1-50 | 10 | at most 6 |
MEDIUM | 1-100 | 7 | at most 7 |
HARD | 1-1000 | 10 | at most 10 |
How it works:
- Each enum constant passes its values to the constructor, so
Difficulty.MEDIUM.maxAttemptsis7. All game rules live in one place. attemptsLeftcounts down with every guess. When it reaches0, the loop stops and the player loses.- Counting up by tens (the second game) wastes guesses. The next section shows why 7 attempts are always enough for 1 to 100 with the right strategy.
Binary Search: The Best Number Guessing Strategy
The smartest strategy is to always guess the middle of the remaining range. Each answer removes half of the possible numbers. This is binary search, the same idea Arrays.binarySearch uses on sorted arrays.
public class ComputerGuesser {
// the computer finds the secret by always guessing the middle of the range
static int solve(int low, int high, int secret) {
int attempts = 0;
while (low <= high) {
int guess = low + (high - low) / 2; // middle, without int overflow
attempts++;
System.out.printf(" try %d: range %d-%d, guess %d%n", attempts, low, high, guess);
if (guess == secret) return attempts;
if (guess < secret) low = guess + 1; // secret is in the upper half
else high = guess - 1; // secret is in the lower half
}
throw new IllegalStateException("Secret was outside the range");
}
public static void main(String[] args) {
System.out.println("Secret 73 in 1-100:");
System.out.println("Solved in " + solve(1, 100, 73) + " attempts");
for (int max : new int[] {100, 1000, 1_000_000}) {
int worstCase = 32 - Integer.numberOfLeadingZeros(max); // floor(log2(max)) + 1
System.out.println("1-" + max + " never needs more than " + worstCase + " guesses");
}
}
}
Secret 73 in 1-100:
try 1: range 1-100, guess 50
try 2: range 51-100, guess 75
try 3: range 51-74, guess 62
try 4: range 63-74, guess 68
try 5: range 69-74, guess 71
try 6: range 72-74, guess 73
Solved in 6 attempts
1-100 never needs more than 7 guesses
1-1000 never needs more than 10 guesses
1-1000000 never needs more than 20 guesses
How it works:
- After a "higher" answer, every number up to the guess is impossible, so
lowmoves toguess + 1. After "lower",highmoves toguess - 1. low + (high - low) / 2finds the middle without overflow.(low + high) / 2can overflow when both values are close toInteger.MAX_VALUE.32 - Integer.numberOfLeadingZeros(max)counts the bits inmax, which equals the worst-case number of guesses. One million numbers need only 20 guesses, because 2^20 is more than one million.- This proves the difficulty table is fair:
MEDIUMandHARDgive exactly as many attempts as a perfect player needs.
Separate Game Logic From Input and Output
The final game has three classes. The first two contain no Scanner and no System.out, so the rules can be checked without typing anything.
The Difficulty Enum
package com.gocourse.guess;
/** Each level sets the range of the secret number and how many guesses are allowed. */
public enum Difficulty {
EASY(50, 10),
MEDIUM(100, 7),
HARD(1000, 10);
private final int maxNumber;
private final int maxAttempts;
Difficulty(int maxNumber, int maxAttempts) {
this.maxNumber = maxNumber;
this.maxAttempts = maxAttempts;
}
public int maxNumber() { return maxNumber; }
public int maxAttempts() { return maxAttempts; }
/** Accepts "1", "easy", "E" and similar answers. */
public static Difficulty parse(String text) {
String value = text.strip().toUpperCase();
for (Difficulty level : values()) {
if (value.equals(String.valueOf(level.ordinal() + 1))
|| level.name().equals(value)
|| level.name().startsWith(value) && !value.isEmpty()) {
return level;
}
}
throw new IllegalArgumentException("Choose 1, 2 or 3");
}
}
How it works:
ordinal()is the position of the constant (0, 1, 2), soordinal() + 1matches the menu numbers 1, 2 and 3.startsWith(value)lets the player typee,meorHARD. The empty-string check stops a blank line from matchingEASY.
The GuessGame Class
package com.gocourse.guess;
import java.util.random.RandomGenerator;
/** One round of the game. It has no Scanner or System.out, so it is easy to test. */
public class GuessGame {
public enum Result { TOO_LOW, TOO_HIGH, CORRECT, GAME_OVER }
private final Difficulty difficulty;
private final int secret;
private int attemptsUsed = 0;
private boolean finished = false;
public GuessGame(Difficulty difficulty, RandomGenerator random) {
this.difficulty = difficulty;
this.secret = random.nextInt(1, difficulty.maxNumber() + 1);
}
public Result guess(int value) {
if (finished) {
throw new IllegalStateException("This round is already over");
}
if (value < 1 || value > difficulty.maxNumber()) {
throw new IllegalArgumentException("Guess between 1 and " + difficulty.maxNumber());
}
attemptsUsed++; // only valid guesses use up an attempt
if (value == secret) {
finished = true;
return Result.CORRECT;
}
if (attemptsUsed == difficulty.maxAttempts()) {
finished = true;
return Result.GAME_OVER;
}
return value < secret ? Result.TOO_LOW : Result.TOO_HIGH;
}
public int attemptsUsed() { return attemptsUsed; }
public int attemptsLeft() { return difficulty.maxAttempts() - attemptsUsed; }
public boolean isFinished() { return finished; }
public Difficulty difficulty() { return difficulty; }
/** Revealed only when the round is over, so the UI cannot leak it early. */
public int secret() {
if (!finished) throw new IllegalStateException("No peeking!");
return secret;
}
}
How it works:
- The constructor receives a
RandomGeneratorinstead of creating one. The app passes a real random generator, while tests passnew Random(7)to get a known secret. This technique is called dependency injection. - An out-of-range guess throws an exception before
attemptsUsed++, so typing mistakes do not cost the player an attempt. - The
secretfield isprivateand the getter refuses to answer until the round is finished, a small example of encapsulation.
Check the Game Rules Without a Keyboard
Because the logic is separate, a short program can confirm that the rules work.
package com.gocourse.guess;
import java.util.Random;
public class GuessGameCheck {
public static void main(String[] args) {
// Random(7) always picks 37 for MEDIUM, so the expected results are known
GuessGame game = new GuessGame(Difficulty.MEDIUM, new Random(7));
System.out.println(game.guess(50) + ", attempts left " + game.attemptsLeft());
System.out.println(game.guess(30) + ", attempts left " + game.attemptsLeft());
System.out.println(game.guess(37) + ", finished " + game.isFinished());
System.out.println("secret = " + game.secret());
try {
game.guess(40);
} catch (IllegalStateException e) {
System.out.println("After the round: " + e.getMessage());
}
GuessGame fresh = new GuessGame(Difficulty.EASY, new Random(7));
try {
fresh.secret();
} catch (IllegalStateException e) {
System.out.println("Before the end: " + e.getMessage());
}
}
}
TOO_HIGH, attempts left 6
TOO_LOW, attempts left 5
CORRECT, finished true
secret = 37
After the round: This round is already over
Before the end: No peeking!
How it works:
- The seed makes the secret predictable, so every line of output can be checked by eye or, later, with JUnit assertions.
- The two
tryblocks prove the safety rules: no guessing after the round ends, and no reading the secret before it ends.
Build the Java Number Guess Game Console App
GuessGameApp handles the menu, the input and the best scores. It adds a --seed option so a whole session can be replayed exactly.
package com.gocourse.guess;
import java.util.EnumMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.random.RandomGenerator;
/** Console front end: java -jar number-guess-game.jar [--seed N] */
public class GuessGameApp {
private final Scanner scanner = new Scanner(System.in);
private final RandomGenerator random;
private final Map<Difficulty, Integer> bestScores = new EnumMap<>(Difficulty.class);
GuessGameApp(RandomGenerator random) {
this.random = random;
}
public static void main(String[] args) {
RandomGenerator random = (args.length == 2 && args[0].equals("--seed"))
? new Random(Long.parseLong(args[1])) // repeatable games for testing
: RandomGenerator.getDefault();
new GuessGameApp(random).run();
}
void run() {
System.out.println("=== GOCOURSE Number Guess Game ===");
do {
Difficulty level = askDifficulty();
if (level == null) break;
playRound(new GuessGame(level, random));
} while (askYesNo("Play again? (y/n): "));
printBestScores();
System.out.println("Thanks for playing!");
}
private void playRound(GuessGame game) {
Difficulty level = game.difficulty();
System.out.printf("I picked a number from 1 to %d. You have %d attempts.%n",
level.maxNumber(), level.maxAttempts());
while (!game.isFinished()) {
String line = readLine("Guess #" + (game.attemptsUsed() + 1) + ": ");
if (line == null) return;
try {
GuessGame.Result result = game.guess(Integer.parseInt(line));
switch (result) {
case TOO_LOW -> System.out.println(" Higher! (" + game.attemptsLeft() + " left)");
case TOO_HIGH -> System.out.println(" Lower! (" + game.attemptsLeft() + " left)");
case CORRECT -> {
System.out.println(" Correct! You needed " + game.attemptsUsed() + " attempts.");
recordScore(level, game.attemptsUsed());
}
case GAME_OVER -> System.out.println(" Out of attempts! It was " + game.secret() + ".");
}
} catch (NumberFormatException e) {
System.out.println(" '" + line + "' is not a whole number.");
} catch (IllegalArgumentException e) {
System.out.println(" " + e.getMessage());
}
}
}
private void recordScore(Difficulty level, int attempts) {
Integer best = bestScores.get(level);
if (best == null || attempts < best) {
bestScores.put(level, attempts);
System.out.println(" New best score for " + level + "!");
}
}
private Difficulty askDifficulty() {
while (true) {
String line = readLine("Difficulty: 1) Easy 2) Medium 3) Hard > ");
if (line == null) return null;
try {
return Difficulty.parse(line);
} catch (IllegalArgumentException e) {
System.out.println(" " + e.getMessage());
}
}
}
private boolean askYesNo(String prompt) {
String line = readLine(prompt);
return line != null && line.toLowerCase().startsWith("y");
}
private String readLine(String prompt) {
System.out.print(prompt);
return scanner.hasNextLine() ? scanner.nextLine().strip() : null;
}
private void printBestScores() {
if (bestScores.isEmpty()) return;
System.out.println("Best scores:");
bestScores.forEach((level, attempts) ->
System.out.println(" " + level + ": " + attempts + " attempts"));
}
}
How it works:
- The
do ... whileloop plays at least one round, then repeats while the player answersy. NumberFormatExceptionis caught beforeIllegalArgumentException. The order matters becauseNumberFormatExceptionis a subclass ofIllegalArgumentException; reversing them would not compile.EnumMapstores one best score per level and prints them in enum order (EASY,MEDIUM,HARD). A lower attempt count is a better score.readLinereturnsnullwhen input ends (Ctrl+D), and every caller handles that, so the game never crashes withNoSuchElementException.
Real-World Example: Package and Play number-guess-game.jar
The project layout follows the same structure as the earlier projects:
number-guess-game/
└── src/
└── com/
└── gocourse/
└── guess/
├── Difficulty.java
├── GuessGame.java
└── GuessGameApp.java
cd number-guess-game
javac -d out src/com/gocourse/guess/*.java
jar --create --file number-guess-game.jar --main-class com.gocourse.guess.GuessGameApp -C out .
java -jar number-guess-game.jar --seed 7
With seed 7, the first MEDIUM secret is always 37 and the next EASY secret is always 15, so this session can be repeated exactly:
=== GOCOURSE Number Guess Game ===
Difficulty: 1) Easy 2) Medium 3) Hard > 2
I picked a number from 1 to 100. You have 7 attempts.
Guess #1: 50
Lower! (6 left)
Guess #2: abc
'abc' is not a whole number.
Guess #2: 200
Guess between 1 and 100
Guess #2: 25
Higher! (5 left)
Guess #3: 37
Correct! You needed 3 attempts.
New best score for MEDIUM!
Play again? (y/n): y
Difficulty: 1) Easy 2) Medium 3) Hard > 4
Choose 1, 2 or 3
Difficulty: 1) Easy 2) Medium 3) Hard > easy
I picked a number from 1 to 50. You have 10 attempts.
Guess #1: 25
Lower! (9 left)
Guess #2: 12
Higher! (8 left)
Guess #3: 18
Lower! (7 left)
Guess #4: 15
Correct! You needed 4 attempts.
New best score for EASY!
Play again? (y/n): n
Best scores:
EASY: 4 attempts
MEDIUM: 3 attempts
Thanks for playing!
A losing round on HARD, played without binary search (seed 1):
=== GOCOURSE Number Guess Game ===
Difficulty: 1) Easy 2) Medium 3) Hard > 3
I picked a number from 1 to 1000. You have 10 attempts.
Guess #1: 1
Higher! (9 left)
Guess #2: 2
Higher! (8 left)
...
Guess #10: 10
Out of attempts! It was 986.
Play again? (y/n): n
Thanks for playing!
How it works:
- Invalid input is free.
abcand200printed errors, but the prompt still saidGuess #2, because only valid guesses count as attempts. - Flexible menu input.
2,easyandeall select a level, while4shows a clear message and asks again. - Binary search wins. Guessing 50, then 25, then 37 (the middle each time) found the
MEDIUMnumber in 3 attempts. Counting up one by one onHARDran out after 10. - Repeatable testing.
--seed 7produced the same secrets every run, so the whole session above can be piped from a file withjava -jar number-guess-game.jar --seed 7 < session.txtand compared with the expected output. - Clean ending. After the last round, the best scores print in level order and the program exits normally.
The next project, the Java Student Manager, moves from a single number to a whole collection of records, with searching, sorting and saving to a file.