Number Guessing Game in Java
Build a CLI number guessing game using loops, conditionals, 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 zero in on the answer. That simple back-and-forth is a surprisingly rich programming challenge.
In this project, you will build a command-line number guessing game in Java that picks a secret number, gives you directional hints after each guess, and rates your performance when you finally nail it.
What You'll Build
You run the program, it challenges you to find its secret number between 1 and 100, and you keep guessing until you crack it. Each wrong guess gets instant feedback, and when you win, you see exactly how many attempts it took and whether you're a mind reader or need more practice.
By the end of this project, you'll have:
- A playable CLI game you can run from the terminal and challenge friends to beat your high score.
- Hands-on experience combining while loops, if/else conditionals, and user input in a single working program.
- A performance rating system that tracks your attempts and tells you how sharp your guessing strategy is.
- Secret Mission: bulletproof input validation and a "play again" loop so your game never crashes and never ends.
Are there any prerequisites?
You'll need Java (JDK) and IntelliJ IDEA installed on your machine. No prior Java experience beyond knowing what a variable is and how to print to the console.
Before We Start
Before we jump into code, let's get clear on what you're building and why it matters for your Java learning path.
This is your moment to lock in the goal before any hands-on work begins.
Create Your Java Project in IntelliJ
Before writing any game logic, you need a project structure and a runnable class. IntelliJ IDEA handles the boilerplate so you can focus on code.
In this step, you'll create a new Java project, add a class file, and run a print statement to confirm everything compiles and executes correctly.
In this step, get ready to:
- Create a new Java project in IntelliJ IDEA.
- Add a NumberGuessingGame class.
- Run the program to verify Java compiles and executes.
Create a new Java project
- Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type IntelliJ IDEA and press Enter to open it.
IntelliJ opens to the Welcome screen.
- Click New Project.
- Select Java from the list on the left.
- In the Name field, type NumberGuessingGame.
- Set Build system to IntelliJ.
- Select your installed JDK from the JDK dropdown.
- Uncheck Add sample code.
- Click Create.
IntelliJ creates and loads your project. You should see the Project tool window on the left with a src folder inside NumberGuessingGame.
Don't see a JDK in the dropdown?
If the JDK dropdown is empty, select Download JDK from the dropdown. Pick the latest available version, confirm the install path, and click Select.
help me set up a JDK in IntelliJ IDEA
Add the NumberGuessingGame class
- In the Project tool window (Alt+1), right-click the src folder.
- Select New, then Java Class.
- Type NumberGuessingGame in the name field and press Enter.
IntelliJ creates the file and opens it in the editor. You should see an empty class declaration: public class NumberGuessingGame {}.
Add a main method and run the program
Every Java program needs a main method as its entry point. This is the method the JDK calls when you run the program.
- Inside the NumberGuessingGame class (between the curly braces), replace the empty body with the following code:
public class NumberGuessingGame {
public static void main(String[] args) {
// Print a test message to confirm the project runs
System.out.println("Number Guessing Game");
}
}
What does this code do?
- public static void main(String[] args) is the entry point Java looks for when running a class. Without it, the program has nothing to execute.
- System.out.println("Number Guessing Game") prints text to the console. This proves the project compiles and runs correctly.
Before you run this, what do you expect to see printed in the console?
- Right-click NumberGuessingGame.java in the editor.
- Select Run 'NumberGuessingGame.main()'.
The console at the bottom of IntelliJ prints Number Guessing Game. Java compiled and ran your code successfully.
Seeing an error instead of output?
- Make sure the class name NumberGuessingGame in your code matches the file name exactly. Java is case-sensitive.
- Check that public static void main(String[] args) is typed exactly as shown. A typo like Main or string (lowercase s) will cause a compile error.
- If you see a red underline anywhere, hover over it to read the error message.
My Java program won't compile in IntelliJ
✔️ Awesome, I've got everything!
Great. Double check you've saved your file (IntelliJ auto-saves, so you're likely all set).
ⓧ I'd like to double check the full code
Your NumberGuessingGame.java should look exactly like this:
public class NumberGuessingGame {
public static void main(String[] args) {
System.out.println("Number Guessing Game");
}
}
Your project is set up and Java is running. Next up, you'll generate a secret number and let the player take their first guess.
Generate a Secret Number and Take One Guess
Your Java project compiles and runs. Now it's time to write the actual game mechanic.
Before building the full game loop, you need the core interaction working: the computer picks a random number, and you get one chance to guess it. This gives you a playable result in under 5 minutes.
In this step, get ready to:
- Generate a random secret number between 1 and 100.
- Read a guess from the player using Scanner.
- Tell the player whether they guessed correctly.
Import the classes and generate a secret number
Java's Random class generates unpredictable numbers. Its nextInt(100) method returns a number from 0 to 99, so adding 1 shifts the range to 1-100.
Java's Scanner class reads input from the terminal. You create one that listens to System.in (the keyboard) and call methods on it to grab whatever the player types.
- In IntelliJ, open NumberGuessingGame.java from the Project tool window (Alt+1).
- Replace the entire contents of the file with this code:
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
// Create a Scanner to read player input from the keyboard
Scanner scanner = new Scanner(System.in);
// Create a Random instance to generate the secret number
Random random = new Random();
// Pick a secret number between 1 and 100
int secretNumber = random.nextInt(100) + 1;
}
}
What does this code do?
- import java.util.Random and import java.util.Scanner bring in the classes you need for randomness and user input.
- new Scanner(System.in) creates a scanner that reads whatever the player types in the console.
- random.nextInt(100) + 1 generates a random integer from 1 to 100. nextInt(100) gives 0-99, so the + 1 shifts it up.
- Save the file with Ctrl+S.
Prompt the player and check their guess
The secret number exists, but the player can't interact with it yet. You need to print a prompt, read the player's guess, and tell them whether they got it right.
- In NumberGuessingGame.java, find the line that says int secretNumber = random.nextInt(100) + 1; and copy the following code below it (still inside the main method):
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I'm thinking of a number between 1 and 100.");
System.out.print("Enter your guess: ");
// Read the player's guess as an integer
int guess = scanner.nextInt();
// Check if the guess matches the secret number
if (guess == secretNumber) {
System.out.println("Congratulations! You guessed the number!");
} else {
System.out.println("Wrong! The number was " + secretNumber + ".");
}
// Release the scanner's resources
scanner.close();
What does this code do?
- System.out.print (without ln) prints the prompt without moving to a new line, so the player's cursor sits right after "Enter your guess: ".
- scanner.nextInt() waits for the player to type a number and press Enter, then returns that number as an int.
- The if/else block compares guess to secretNumber. If they match, the player wins. Otherwise, the game reveals the answer.
- scanner.close() releases the scanner's resources when the program is done reading input.
- Save the file with Ctrl+S.
Run the game and play one round
Before you run this, think: what are the odds you guess the number correctly on your first and only try?
- Right-click anywhere in the editor and select Run 'NumberGuessingGame.main()'.
- Type a number between 1 and 100 in the console at the bottom of IntelliJ and press Enter.
You have a 1-in-100 chance of guessing correctly. You'll almost certainly see "Wrong! The number was X." followed by the program exiting. The game works, but one guess is all you get.
Seeing an error instead of the prompt?
- If you see a red underline on Scanner or Random, make sure the two import lines are at the very top of the file, above the public class line.
- If the console says "cannot find symbol", check that your variable names match exactly: scanner (lowercase s) and secretNumber (camelCase).
Why is my Java program not compiling?
✔️ Awesome, I've got everything!
Great. Make sure you've saved NumberGuessingGame.java before moving on.
ⓧ I'd like to double check the full code
Here's the complete NumberGuessingGame.java at this point. Make sure yours matches exactly:
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int secretNumber = random.nextInt(100) + 1;
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I'm thinking of a number between 1 and 100.");
System.out.print("Enter your guess: ");
int guess = scanner.nextInt();
if (guess == secretNumber) {
System.out.println("Congratulations! You guessed the number!");
} else {
System.out.println("Wrong! The number was " + secretNumber + ".");
}
scanner.close();
}
}
Your game works. But with only one guess and a 1-in-100 chance of winning, it feels more like a coin flip than a game. Next up, you'll add a loop that lets the player keep guessing until they find the number, with hints pointing them in the right direction.
Add the Game Loop with Higher/Lower Hints
You just played your game and discovered the problem. With a single guess against a number between 1 and 100, you have a 1% chance of winning.
The fix is a while loop that keeps asking for guesses until the player gets it right. You will also add directional hints ("too high" or "too low") so the player can converge on the answer instead of guessing blindly.
In this step, get ready to:
- Add a boolean flag that controls when the loop stops.
- Replace the single-guess logic with a while loop and higher/lower hints.
- Play through the full game and guess the number.
Add a loop control variable
A while loop needs a condition to check on every iteration. You will use a boolean variable that starts as false and flips to true only when the player guesses correctly.
- In NumberGuessingGame.java, find this line:
int secretNumber = random.nextInt(100) + 1;
- Add this new line directly below it:
boolean hasGuessedCorrectly = false;
What is a boolean flag?
A boolean variable holds only two values: true or false. When used to control a loop, it acts like a switch. The loop keeps running while the flag is false, and stops the moment you flip it to true.
Replace the single guess with a game loop
Now you will swap the old one-shot guess logic with a while loop. The loop asks for a guess on every iteration and gives a directional hint until the player finds the number.
- Find and select the following block of code (everything from the Enter your guess print line through the closing } of the else block):
System.out.print("Enter your guess: ");
int guess = scanner.nextInt();
if (guess == secretNumber) {
System.out.println("Congratulations! You guessed the number!");
} else {
System.out.println("Wrong! The number was " + secretNumber + ".");
}
- Delete that entire block and replace it with the following code:
System.out.println("Can you guess what it is?");
// Keep looping until the player guesses correctly
while (!hasGuessedCorrectly) {
System.out.print("Enter your guess: ");
int guess = scanner.nextInt();
// Give directional feedback based on the guess
if (guess < secretNumber) {
System.out.println("Too low! Try a higher number.");
} else if (guess > secretNumber) {
System.out.println("Too high! Try a lower number.");
} else {
hasGuessedCorrectly = true;
System.out.println("Congratulations! You guessed the number!");
}
}
What does this code do?
The while (!hasGuessedCorrectly) loop runs as long as the flag is false. The ! means "not", so the condition reads: "while the player has NOT guessed correctly, keep going."
Inside the loop, the if/else-if/else chain replaces the old simple equality check. It now gives three possible responses: too low, too high, or correct. Only the correct branch flips the flag to true, which ends the loop on the next check.
- Save NumberGuessingGame.java.
Before you run the program, think about what will happen if you guess a number that is too high. What do you expect to see?
- Right-click the file and select Run 'NumberGuessingGame.main()'.
- Guess wrong on purpose. Type a number you know is too high (like 99) and press Enter.
The program prints "Too high! Try a lower number." and immediately asks for another guess. Keep guessing until you get it right. When you nail it, the game prints "Congratulations! You guessed the number!" and exits.
The binary search shortcut
You can always find the number in 7 or fewer guesses by splitting the remaining range in half each time. Start at 50, then go to 25 or 75 depending on the hint, and keep halving. This is the same logic behind binary search algorithms.
Program runs but never stops looping?
Make sure the else branch inside your while loop includes hasGuessedCorrectly = true;. Without that line, the loop condition never changes and the game never ends.
If you are stuck in an infinite loop, press Ctrl+C in the console to stop the program.
Help me debug my while loop that never exits.
✔️ Awesome, I've got everything!
Great. Double check you have saved your file.
ⓧ I'd like to double check the full code
Your file has two sections of code that you edited in this step. Scroll up and confirm each is present in order:
- The boolean hasGuessedCorrectly = false; declaration directly after the secretNumber line.
- The welcome messages ending with "Can you guess what it is?" (not the old "Enter your guess: " line).
- The while (!hasGuessedCorrectly) loop containing the input prompt and the if/else-if/else chain with "Too low!", "Too high!", and the congratulations message.
- scanner.close(); after the closing brace of the while loop.
Your game is now fully playable. You can always find the secret number by following the hints. Next up, you will track how many attempts the player takes and rate their performance.
Track Attempts and Rate Performance
Your game loop works. You can guess until you find the number, and the hints guide you there every time.
But right now there's no sense of how well you played. Did you nail it in 3 guesses or stumble through 20? Adding an attempt counter and performance tiers turns this from a puzzle into a challenge you want to replay and beat.
In this step, get ready to:
- Add a counter that tracks how many guesses the player takes.
- Display the attempt count and a performance rating when the game ends.
Add an attempt counter
To know how many guesses a player takes, you need a variable that starts at zero and goes up by one each time through the loop. This is a counter pattern you'll use constantly in Java.
- In NumberGuessingGame.java, find the line that declares secretNumber:
int secretNumber = random.nextInt(100) + 1;
boolean hasGuessedCorrectly = false;
- Add a new line int attempts = 0; between those two lines, so the area now looks like this:
int secretNumber = random.nextInt(100) + 1;
int attempts = 0;
boolean hasGuessedCorrectly = false;
- Now find the line inside your while loop that reads the player's guess:
int guess = scanner.nextInt();
- Add attempts++; on the next line, so it looks like this:
int guess = scanner.nextInt();
attempts++;
What does attempts++ do?
The ++ operator adds 1 to the variable. Every time the loop runs (meaning the player made a guess), the counter goes up by one. By placing it right after scanner.nextInt(), every guess gets counted regardless of whether it was too high, too low, or correct.
Rate the player's performance
The counter tracks guesses, but it's not visible to the player yet. You need to print it after the loop ends, along with a rating that gives the result some personality.
- Find the closing } brace of your while loop. Add the following code between that closing brace and the scanner.close(); line:
// Display the total number of guesses
System.out.println("It took you " + attempts + " attempts.");
// Rate performance based on attempt count
if (attempts <= 5) {
System.out.println("Amazing! You're a mind reader!");
} else if (attempts <= 10) {
System.out.println("Great job! You've got solid intuition.");
} else {
System.out.println("You got there in the end! Keep practicing.");
}
What does this code do?
This code only runs after the while loop exits (meaning the player guessed correctly). It uses the attempts counter that was incrementing during the loop to tell the player their score.
The if/else-if/else chain checks the count against thresholds. Five or fewer is excellent. Six to ten is solid. Anything above ten gets a gentle nudge to keep practicing.
- Save NumberGuessingGame.java.
Before you run the game, think about this: if you use binary search logic (always guess the middle of the remaining range), how many attempts should it take to find a number between 1 and 100?
- Right-click the file and select Run 'NumberGuessingGame.main()'.
- Play through the game and guess the number.
After the congratulations message, you see "It took you X attempts." followed by a performance rating that changes based on your attempt count. Try playing again and aiming for 7 or fewer guesses. The optimal strategy (always guess the midpoint of the remaining range) guarantees you find any number in at most 7 attempts.
Not seeing the attempt count?
Make sure the performance rating code is placed after the while loop's closing brace but before scanner.close();. If it's inside the loop, it will print after every guess instead of just at the end.
Check that attempts++ is inside the loop body, not outside. If the count always shows 0, the increment is in the wrong place.
Still stuck? Help me figure out why my attempt counter isn't working in my Java guessing game.
✔️ Awesome, I've got everything!
Great. Make sure you have saved NumberGuessingGame.java and the game runs with attempt tracking and a performance rating.
ⓧ I'd like to double check the full code
Your file is over 30 lines now, so scroll through and confirm these pieces are all in place, in order:
- Imports for java.util.Random and java.util.Scanner at the top.
- Scanner and Random instances created inside main.
- Three variable declarations: secretNumber, then attempts = 0, then hasGuessedCorrectly = false.
- Three welcome/prompt System.out.println lines.
- The while (!hasGuessedCorrectly) loop with scanner.nextInt(), then attempts++, then the if/else-if/else chain for hints.
- After the loop: the "It took you X attempts." print line, followed by the performance rating if/else-if/else chain.
- scanner.close(); as the very last line before the closing braces.
You now have a complete, playable number guessing game. It generates a secret number, gives directional hints, counts your attempts, and rates your performance. Next up, you'll make it bulletproof by handling bad input and adding a replay loop in the Secret Mission.
Secret mission
Bulletproof Input and Play Again
Right now, typing "abc" instead of a number crashes your game instantly. Real programs handle bad input gracefully. In this mission, you'll add input validation and a play-again loop so your game never crashes and never ends.
Clean Up Your Resources
Clean Up Your Resources
Decide whether to keep your resources running, pause them to come back later, or delete them entirely. This project runs entirely locally, so there are no ongoing costs.
Resources you used:
- The NumberGuessingGame IntelliJ IDEA project (local files on your machine).
Keep everything running
No action needed. Choose this if you want to keep playing the game or plan to extend it further.
- Your NumberGuessingGame project stays in IntelliJ IDEA, ready to open and run anytime.
- The project takes minimal disk space (a single Java file plus IntelliJ metadata).
Pause - I'll come back to this later
Close the project to free up IntelliJ IDEA for other work. Your files stay on disk.
- In IntelliJ IDEA, click File, then Close Project.
- To reopen later, launch IntelliJ IDEA and select NumberGuessingGame from the recent projects list on the Welcome screen.
Delete - I don't want to use this again
Remove the project from IntelliJ IDEA and delete the files from your machine.
- In IntelliJ IDEA, click File, then Close Project to return to the Welcome screen.
- On the Welcome screen, right-click NumberGuessingGame in the recent projects list and select Remove from Recent Projects.
- Open File Explorer and navigate to the folder where you created the project (by default, this is inside your user folder under IdeaProjects).
- Delete the NumberGuessingGame folder.
That's a Wrap!
That's a Wrap!
Nice work! You just built a complete command-line game from scratch using Java fundamentals. From a blank class file to a polished, replayable number guessing game with performance ratings and crash-proof input handling.
You've learned how to:
- Built a complete CLI game combining while loops, if/else conditionals, and user input into a single working program.
- Used Scanner to read player guesses from the terminal and Random to generate unpredictable secret numbers.
- Tracked game state across loop iterations with counter variables and boolean flags to control flow and rate performance.
- Secret Mission: Handled invalid input gracefully and added a replay loop with nested while structures so the game never crashes and never ends.
Ready to quiz yourself?