Guess the Number Game: Build a Fun Interactive Project

Introduction

In this chapter you will build a complete Guess the Number game in Java. The program picks a random integer from 1 to 100, reads guesses with Scanner, and uses conditionals and loops to guide the player. When they win, you print attempt count and guess history.

This project feels like a real game while reinforcing core control flow.

Prerequisites

Project Goal

Rules:

  • Generate one random integer in 1–100 (inclusive)
  • User guesses repeatedly
  • After each guess: print Too low or Too high
  • On success, print:
    • success message
    • total valid attempts
    • all previous guesses

1) Generate a Secret Number with Random

java
import java.util.Random;
 
Random random = new Random();
int secretNumber = random.nextInt(100) + 1;  // 1 .. 100 inclusive

nextInt(100) returns 0..99; adding 1 shifts to 1..100.

Tip

Development Tip

While debugging, temporarily print secretNumber to verify logic—remove it before sharing the game.

2) Tracking Variables

java
import java.util.ArrayList;
import java.util.List;
 
List<Integer> guessHistory = new ArrayList<>();
int attempts = 0;

ArrayList is a resizable list from the standard library. You will study collections formally in Collections Overview; here it is the simplest way to store unknown guess count.

Array-only alternative: int[] guesses = new int[100]; with a separate count index—works but ArrayList is clearer.

3) Core Game Loop

java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
 
public class GuessTheNumberGame {
    public static void main(String[] args) {
        Random random = new Random();
        int secretNumber = random.nextInt(100) + 1;
 
        List<Integer> guessHistory = new ArrayList<>();
        int attempts = 0;
 
        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
                System.out.print("Guess a number between 1 and 100: ");
 
                if (!scanner.hasNextInt()) {
                    System.out.println("Please enter a valid integer.");
                    scanner.next();  // discard invalid token
                    continue;
                }
 
                int guess = scanner.nextInt();
 
                if (guess < 1 || guess > 100) {
                    System.out.println("Out of range. Enter 1–100.");
                    continue;
                }
 
                attempts++;
                guessHistory.add(guess);
 
                if (guess < secretNumber) {
                    System.out.println("Too low.");
                } else if (guess > secretNumber) {
                    System.out.println("Too high.");
                } else {
                    System.out.println("Correct! The number was " + secretNumber + ".");
                    System.out.println("You used " + attempts + " attempts.");
                    System.out.println("Guess history: " + guessHistory);
                    break;
                }
            }
        }
    }
}

Invalid input and out-of-range guesses do not increment attempts in this design—friendly for beginners.

4) Understand the Flow

  1. InputScanner reads an integer
  2. Validate — reject bad tokens and out-of-range values
  3. Process — compare guess to secretNumber
  4. Output — hints or final summary
  5. Repeat until correct

This input → validate → process → output loop appears in CLIs, APIs, and games at every scale.

5) Optional Upgrades

After the base game works, try:

  • Difficulty modes: 1–50, 1–100, 1–500 (nextInt(bound) + 1)
  • Max attempts: stop after N wrong tries
  • Replay: ask Play again? (y/n) in an outer loop
  • Best score: track fewest attempts across rounds
java
System.out.print("Play again? (y/n): ");
String again = scanner.next();
if (!again.equalsIgnoreCase("y")) {
    break;
}

Surprise Practice: Smart Hints

After each wrong guess, print distance hint:

  • Very close if Math.abs(guess - secretNumber) <= 3
  • Close if difference <= 10
  • Far otherwise

At the end, print the closest guess from guessHistory (loop and track minimum distance).

You are combining game logic with lightweight analytics—excellent practice.

Common Beginner Mistakes

Mistake 1: Wrong Random Range

java
random.nextInt(100);      // 0..99 — off by one for 1..100 game
random.nextInt(101);      // 0..100 — includes 0
random.nextInt(100) + 1;  // 1..100 — correct

Mistake 2: Forgetting to Record History

Without guessHistory.add(guess), the final summary is empty.

Mistake 3: Counting Invalid Input as Attempts

Decide your rules explicitly; the sample code skips invalid guesses.

Mistake 4: Scanner Has No More Tokens

After invalid input, scanner.next() clears the bad token before retrying.

What’s Next

You have finished the core procedural Java track through small games. Next, enter Object-Oriented Programming and learn how classes organize larger programs.

FAQ

Why Random instead of Math.random()?

Both work. java.util.Random is explicit and common in teaching examples. Math.random() returns 0.0 <= x < 1.0 and needs scaling.

Should invalid guesses count as attempts?

Your choice. The sample does not count them—most beginner-friendly.

Why use ArrayList instead of an array?

Guess count is unknown upfront. ArrayList grows automatically. Fixed arrays need a max size and index counter.

Can I split this into methods?

Yes—readGuess(), compareGuess(), printSummary()—after Methods.

How do I avoid printing the secret in production?

Never log secrets in real auth systems; here, simply remove debug println of secretNumber.