Build a Number Guessing Game in Java

Write a Java console game using variables, loops, and user input.

Introduction

30 Second Summary

Think about the last time you played a guessing game with a friend. They pick a number, you guess, and they tell you "higher" or "lower" until you nail it. It is a simple concept, but building a computer version from scratch teaches you the fundamental building blocks of programming.

In this project, you will build a Number Guessing Game in Java where the computer picks a secret number and gives you hints until you guess correctly.

What You'll Build

A command-line Java game that generates a random number between 1 and 100, reads player guesses from the keyboard, and responds with "too high" or "too low" hints until the player wins.

By the end of this project, you'll have:

  • A working Java program built entirely from scratch that you can compile and run from the terminal.
  • Hands-on experience with core Java concepts: variables, conditionals, loops, and user input.
  • An interactive game loop that tracks your guesses and congratulates you when you win.
  • Secret Mission: Add a maximum attempts limit and a "play again?" feature so the game keeps going without restarting the program.

Are there any prerequisites?

None. This project assumes you have VS Code with the Extension Pack for Java and OpenJDK 25 already installed. Step 1 walks you through verifying everything is working before you write any game code.

Set Up Your Project

Before you can build a game, you need a workspace where you can write, compile, and run Java code.

In this step, you'll confirm your Java tools are working, create a project folder, and test everything with a simple program.

In this step, get ready to:
  • Verify Java is ready in your terminal.
  • Create a project folder and Java file.
  • Compile and run a Hello World program.
Verify your Java installation

VS Code has a built-in terminal that lets you run commands without leaving the editor.

  • Open the integrated terminal by pressing Ctrl+` (backtick key, usually above Tab).
  • Check your Java runtime by running this command:
java -version

You should see output starting with openjdk version "25 followed by build details.

  • Check the Java compiler by running this command:
javac -version

You should see javac 25 followed by a version number.

What are these two commands?

java -version checks the Java runtime, which runs your compiled programs.

javac -version checks the Java compiler, which translates your source code into something the runtime can execute. You need both to build and run Java programs.

Not seeing version 25?

If you see a lower version number, your system may be using an older Java installation. Make sure OpenJDK 25 Temurin is installed and that your system PATH points to it.

If you see a "command not found" error, the JDK is not installed or not on your PATH. Visit the Adoptium website to download and install OpenJDK 25 Temurin.

Help me troubleshoot my Java installation

Create your project folder and Java file

Every Java project needs a folder to live in. You'll create one on your Desktop so it's easy to find.

  • Move to your Desktop by running this command:
cd ~/Desktop
  • Create your project folder and move into it by running these commands:
mkdir number-guessing-game
cd number-guessing-game
  • Confirm the folder exists by running:
ls ~/Desktop

You should see number-guessing-game in the output.

  • Now open this folder in VS Code. Click File in the top menu bar.
  • Click Open Folder.
  • Navigate to your Desktop, select the number-guessing-game folder, and click Open.

VS Code reloads with your project folder as the workspace. You'll see number-guessing-game in the Explorer sidebar on the left.

  • In the Explorer sidebar, hover over the folder name and click the New File icon (a page with a plus sign).
  • Type NumberGuesser.java and press Enter.

The file opens in the editor, ready for you to write code.

Why does the filename matter?

In Java, the filename must exactly match the public class name inside it. Since your class will be called NumberGuesser, the file must be NumberGuesser.java. Getting this wrong causes a compiler error.

Don't see the Explorer sidebar?

If the sidebar is hidden, press Cmd+Shift+E (macOS) or Ctrl+Shift+E (Windows) to open it.

If you see a "Trust" prompt when opening the folder, click Yes, I trust the authors to continue.

Help me find the Explorer sidebar or New File button in VS Code

Write and run a Hello World program

A Hello World program is the simplest possible Java program. It proves your entire toolchain works before you add game logic.

  • In NumberGuesser.java, type the following code:
// Define the main class (must match the filename)
public class NumberGuesser {
    // Entry point - Java starts running here
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

What does this code do?

public class NumberGuesser creates a class. Every Java program needs at least one class, and the class name must match the filename.

public static void main(String[] args) is the entry point. When you run the program, Java looks for this exact method signature and starts executing from here.

System.out.println prints text to the terminal followed by a new line.

  • Save the file by pressing Cmd+S (macOS) or Ctrl+S (Windows).
  • Open the terminal by pressing Ctrl+` if it's not already visible.
  • Compile your program by running this command:
javac NumberGuesser.java
  • Run your compiled program by running this command:
java NumberGuesser

You should see Hello, World! printed in the terminal.

Why two separate commands?

javac (Java Compiler) translates your .java source file into a .class file containing bytecode. This is the compile step.

java (Java Runtime) reads that bytecode and executes it. This is the run step. You'll repeat this compile-then-run cycle every time you change your code.

Seeing an error when compiling?

If you see an error mentioning the class name, make sure NumberGuesser in your code matches the filename NumberGuesser.java exactly (capitalization matters).

If you see a "file not found" error, make sure your terminal is inside the number-guessing-game folder. Run ls to check if NumberGuesser.java is listed.

Help me fix my Java compilation error

✔️ Awesome, I've got everything!

Great. Double check you've saved NumberGuesser.java and that your terminal printed Hello, World! successfully.

ⓧ I'd like to double check the full code

Here's what NumberGuesser.java should look like at this point:

public class NumberGuesser {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Your environment is ready and proven. Next up, you'll start building the actual game by generating a secret random number.

Generate the Secret Number

Your Java environment is ready and running. Now it's time to make your game interesting by giving it a secret for the player to uncover.

Every guessing game needs an element of surprise. Java's Random class can generate unpredictable numbers each time the program runs, which is exactly what we need for this game.

In this step, get ready to:
  • Generate a random secret number between 1 and 100.
  • Declare variables to track the player's guess and attempt count.
  • Print a welcome message and verify the random number changes each run.
Import Random and set up game variables

The Hello World program confirmed your environment works. Now you'll replace it with the actual game logic.

  • Replace the entire contents of NumberGuesser.java with the following code:
import java.util.Random;

public class NumberGuesser {
    public static void main(String[] args) {
        // Create a random number generator
        Random random = new Random();

        // Generate a secret number between 1 and 100
        int secretNumber = random.nextInt(100) + 1;
        // Track the player's current guess and total attempts
        int guess = 0;
        int attempts = 0;
    }
}

What does this code do?

import java.util.Random; loads Java's built-in random number library so you can use it in your program.

Random random = new Random(); creates a random number generator object. random.nextInt(100) + 1 generates a number between 1 and 100. The nextInt(100) method returns 0 to 99, so adding 1 shifts the range to 1 to 100.

The guess and attempts variables start at 0. You'll use them in later steps to track what the player enters and how many tries they take.

You won't see any output yet. The next chunk adds the welcome message and prints the secret number so you can verify it works.

Add the welcome message and verify

Now you need output so the player knows the game has started. You'll also add a temporary debug line that prints the secret number, so you can confirm it's working.

  • In NumberGuesser.java, find the line that says int attempts = 0; and copy the following code below it:
        System.out.println("=== Number Guessing Game ===");
        System.out.println("I'm thinking of a number between 1 and 100.");
        System.out.println("Can you guess what it is?");
        System.out.println();
        // Temporary line to verify the random number works
        System.out.println("DEBUG: secret number is " + secretNumber);

What does this code do?

The first three println statements display a welcome banner so the player knows the game has started. System.out.println() with no argument prints a blank line for visual spacing.

The DEBUG line is temporary. It lets you see the secret number in the console so you can confirm it changes each run. You'll remove this line once you build the full game loop.

  • Save NumberGuesser.java.
  • Compile and run your program by running these commands in the terminal:
javac NumberGuesser.java
java NumberGuesser
  • You should see the welcome message followed by a line like DEBUG: secret number is 42 (your number will be different).
  • Run java NumberGuesser again. The number should change each time, confirming your random generation works.

Seeing a compile error?

Check that import java.util.Random; is the very first line of your file, above the public class line. Java requires imports before the class declaration.

Make sure there are no leftover lines from the Hello World program. The System.out.println("Hello, World!"); line should be gone.

help me fix a compile error in my NumberGuesser.java file

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

import java.util.Random;

public class NumberGuesser {
    public static void main(String[] args) {
        Random random = new Random();

        int secretNumber = random.nextInt(100) + 1;
        int guess = 0;
        int attempts = 0;

        System.out.println("=== Number Guessing Game ===");
        System.out.println("I'm thinking of a number between 1 and 100.");
        System.out.println("Can you guess what it is?");
        System.out.println();
        System.out.println("DEBUG: secret number is " + secretNumber);
    }
}

Your game now picks a secret number every time it runs. Next up, you'll let the player actually guess that number by reading keyboard input.

Read the Player's Guess

Your game now picks a secret number and prints it to the terminal. The next piece of the puzzle is letting the player actually guess that number.

Java programs read keyboard input through a class called Scanner. In this step, you'll wire up a Scanner to capture the player's guess from the terminal.

In this step, get ready to:
  • Import Scanner and create a Scanner object to read from the keyboard.
  • Prompt the player for a guess and read their input.
  • Confirm the input works by printing it back and clean up the Scanner.
Import Scanner and create a Scanner object

Scanner is a built-in Java class that reads text from an input source. You'll connect it to System.in, which represents the keyboard.

  • In NumberGuesser.java, find the import line at the very top of your file:
import java.util.Random;
  • Add this new import line directly above it:
import java.util.Scanner;
  • Now find this line inside your main method:
Random random = new Random();
  • Add this line directly above it:
Scanner scanner = new Scanner(System.in);

What is Scanner?

Scanner is Java's built-in tool for reading input. By passing System.in to its constructor, you're telling it to listen to whatever the player types in the terminal.

The import java.util.Scanner line at the top lets Java know where to find the Scanner class. Without it, the compiler would not recognize the name.

Add the guessing prompt and read the player's input

With Scanner ready, you can now ask the player for a number and capture their response.

  • In NumberGuesser.java, find the DEBUG line near the bottom:
System.out.println("DEBUG: secret number is " + secretNumber);
  • Copy the following code below that DEBUG line:
// Prompt the player and read their guess
System.out.print("Enter your guess: ");
guess = scanner.nextInt();

// Confirm what was entered
System.out.println("You entered: " + guess);

// Close the scanner to free resources
scanner.close();

What does this code do?

  • System.out.print displays the prompt without moving to a new line, so the player types their answer on the same line.
  • scanner.nextInt() pauses the program and waits for the player to type a whole number, then stores it in guess.
  • The confirmation line prints the number back so you can verify the input was captured correctly.
  • scanner.close() releases the keyboard resource when the program is done.
  • Save NumberGuesser.java.
  • Compile and run your program by running these commands in the terminal:
javac NumberGuesser.java
java NumberGuesser
  • The program prints the welcome message and DEBUG number, then pauses at Enter your guess: waiting for you to type a number.
  • Type any number (e.g. 42) and press Enter.
  • You should see You entered: 42 printed back in the terminal.

Seeing a compilation error?

  • Check that import java.util.Scanner; is on its own line above import java.util.Random;. Both imports must be at the very top of the file, outside the class.
  • Make sure Scanner scanner = new Scanner(System.in); is inside the main method (between the curly braces), not outside the class.
  • Confirm that scanner.close(); appears before the closing braces of main and the class.

Help me fix my Scanner compilation error

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

Here's the full NumberGuesser.java file as it should look right now:

import java.util.Scanner;
import java.util.Random;

public class NumberGuesser {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        int secretNumber = random.nextInt(100) + 1;
        int guess = 0;
        int attempts = 0;

        System.out.println("=== Number Guessing Game ===");
        System.out.println("I'm thinking of a number between 1 and 100.");
        System.out.println("Can you guess what it is?");
        System.out.println();
        System.out.println("DEBUG: secret number is " + secretNumber);

        System.out.print("Enter your guess: ");
        guess = scanner.nextInt();
        System.out.println("You entered: " + guess);

        scanner.close();
    }
}

Your game can now read what the player types. Next up, you'll wrap this in a loop and add the "too high" and "too low" hints that make it a real guessing game.

Build the Game Loop

Your program can read a number from the keyboard and you have all the variables ready to track the game. The problem is that it only accepts one guess and immediately exits.

A real guessing game keeps going until the player gets it right. In this step, you'll wrap your code in a loop and add conditional logic that gives helpful hints after each guess.

In this step, get ready to:
  • Wrap the guessing code in a while loop that repeats until the player guesses correctly.
  • Add if/else if/else logic that gives high or low feedback after each guess.
  • Remove the debug output and play the complete game end-to-end.
Wrap the guessing logic in a while loop

Right now your program reads one guess and stops. A while loop lets you repeat a block of code as long as a condition is true.

  • In NumberGuesser.java, find these three lines below the DEBUG printout:
        System.out.print("Enter your guess: ");
        guess = scanner.nextInt();
        System.out.println("You entered: " + guess);
  • Replace those three lines with this while loop:
        // Keep asking until the player guesses correctly
        while (guess != secretNumber) {
            System.out.print("Enter your guess: ");
            guess = scanner.nextInt();
            attempts++;
        }

What does this code do?

The while (guess != secretNumber) condition checks whether the player's current guess matches the secret number. As long as it does not match, the loop keeps running.

Inside the loop, scanner.nextInt() waits for the player to type a new number. Then attempts++ adds one to the attempt counter each time through the loop.

  • Save NumberGuesser.java.
  • Compile and run by entering these commands in the terminal:
javac NumberGuesser.java
java NumberGuesser
  • Use the DEBUG number to guess correctly on purpose. The program should exit only when you type the exact secret number.

Program doesn't stop looping?

Make sure the while condition uses != (not equals). If you accidentally typed ==, the loop runs only when the guess matches, which is the opposite of what you want.

If the program seems stuck, press Ctrl+C in the terminal to force-stop it.

help me debug my while loop

Add conditional feedback logic

The loop works, but it gives no feedback. The player has no idea whether their guess was close or wildly off.

  • In NumberGuesser.java, find the attempts++; line inside your while loop.
  • Add this if/else if/else block directly below attempts++;:
            // Give the player feedback on their guess
            if (guess > secretNumber) {
                System.out.println("Too high! Try a lower number.");
            } else if (guess < secretNumber) {
                System.out.println("Too low! Try a higher number.");
            } else {
                System.out.println("Correct! You guessed it in " + attempts + " attempts!");
            }

What does this code do?

This if/else if/else chain checks three possible outcomes for each guess.

  • If guess > secretNumber: the player overshot, so print "Too high!" to nudge them lower.
  • If guess < secretNumber: the player undershot, so print "Too low!" to nudge them higher.
  • Otherwise (else): the guess must be equal, so print the winning message with the attempt count.
  • Save NumberGuesser.java, compile, and run:
javac NumberGuesser.java
java NumberGuesser
  • Try guessing a number you know is too high, then too low. You should see "Too high! Try a lower number." or "Too low! Try a higher number." after each wrong guess.

Seeing the wrong hint?

Double-check that the greater-than and less-than symbols point the right direction. The condition guess > secretNumber means the guess is larger than the answer, so the hint should say "Too high!"

Also confirm the if/else block is placed inside the while loop's curly braces, not after the closing }.

help me fix my if/else logic

Remove the debug output and play the full game

The DEBUG line was helpful during development, but it ruins the game for real play. Time to remove it and enjoy the final product.

  • In NumberGuesser.java, find this line:
        System.out.println("DEBUG: secret number is " + secretNumber);
  • Delete the entire line.
  • Save NumberGuesser.java, then compile and run:
javac NumberGuesser.java
java NumberGuesser
  • Play the game for real this time. You should see "Too high! Try a lower number." or "Too low! Try a higher number." after wrong guesses, and "Correct! You guessed it in X attempts!" when you win.

Getting a compile error?

If javac reports an error, check that you deleted only the DEBUG line and did not accidentally remove a curly brace or semicolon nearby.

help me fix my compile error

✔️ Awesome, I've got everything!

Great. Double check you've saved NumberGuesser.java and the game plays all the way through.

ⓧ I'd like to double check the full code

Here is the complete NumberGuesser.java file at this point:

import java.util.Scanner;
import java.util.Random;

public class NumberGuesser {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        int secretNumber = random.nextInt(100) + 1;
        int guess = 0;
        int attempts = 0;

        System.out.println("=== Number Guessing Game ===");
        System.out.println("I'm thinking of a number between 1 and 100.");
        System.out.println("Can you guess what it is?");
        System.out.println();

        while (guess != secretNumber) {
            System.out.print("Enter your guess: ");
            guess = scanner.nextInt();
            attempts++;

            if (guess > secretNumber) {
                System.out.println("Too high! Try a lower number.");
            } else if (guess < secretNumber) {
                System.out.println("Too low! Try a higher number.");
            } else {
                System.out.println("Correct! You guessed it in " + attempts + " attempts!");
            }
        }

        scanner.close();
    }
}

Your Number Guessing Game is fully playable. You've combined loops, conditionals, and user input into a real interactive program. Next up, the Secret Mission challenges you to add an attempt limit and a play-again feature.

Secret mission

Add a Max Attempts Limit and Play Again

Your game works, but there's no penalty for guessing forever. Can you add a maximum attempts limit that reveals the answer if the player fails? And while you're at it, let the player start a new round without restarting the program.

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely locally, so there are no ongoing costs. Decide whether to keep your project files or delete them.

Resources you used:

  • The number-guessing-game folder on your Desktop (contains NumberGuesser.java and compiled .class files).

Keep everything running

No action needed. Choose this if you want to keep playing the game or continue experimenting with the code.

  • Your number-guessing-game folder stays on your Desktop. You can recompile and run the game anytime.

Pause - I'll come back to this later

Since this is a local project with no running processes, there is nothing to pause. Your files stay on disk until you decide to delete them.

  • No action needed. The project uses no background services or memory while idle.

Delete - I don't want to use this again

Remove all project files from your machine.

  • Delete the project folder by running this command in your terminal.

macOS

rm -rf ~/Desktop/number-guessing-game

Windows

rmdir /s /q %USERPROFILE%\Desktop\number-guessing-game
  • Confirm the folder is gone by checking your Desktop. You should no longer see number-guessing-game listed.

Nice Work!

Nice Work!

Nice work! You just built a fully interactive Number Guessing Game in Java, completely from scratch.

You've learned how to:

  • Built a complete Java program from scratch using variables and data types (int, String) to store and manage game state.
  • Read keyboard input with Scanner and generated random numbers with the Random class to create an interactive experience.
  • Used a while loop to repeat actions until a condition is met, and if/else if/else logic to make decisions based on player input.
  • Secret Mission: Added attempt limits, game-over conditions, and a play-again loop to make the game replayable.

Ready to quiz yourself?