Number Guessing Game In Java

by | Apr 7, 2023 | Basic Coding, Coding, Java

Introduction of the Project

In this Java tutorial, we will explore how to build a Number Guessing Game in Java. The Number Guessing Game is a simple yet fun project that allows a player to guess a random number within a given range, and the program provides hints on whether the guessed number is higher or lower than the target number. This project is a great way to familiarize yourself with fundamental Java programming concepts such as random number generation, conditional statements, loops, and user input/output.

Whether you are a beginner starting your coding journey in Java or an experienced programmer looking to expand your Java skills, this tutorial will provide you with a step-by-step guide on building a Number Guessing Game in Java. So let’s get started and have some coding fun!



As the name suggests, this game is a very simple game where a user will get a certain number of tries to guess correctly a number generated randomly by the program. If the user can guess the number correctly within the number of tries, he/she will win the game. If not, the user will lose the game and can play again.


Before you start building a Number Guessing Game in Java, you should have some prerequisites in place. Here are the key requirements:

1. Java Development Environment: You need to have Java Development Kit (JDK) installed on your computer. JDK is a software development kit that includes the Java compiler, runtime environment, and other tools needed for Java development.

2. Text Editor or Integrated Development Environment (IDE): You’ll need a text editor or an Integrated Development Environment (IDE) to write and edit Java code. Some popular IDEs for Java development are Eclipse, IntelliJ IDEA, and NetBeans. Choose the one that you are most comfortable with or prefer.

3. Basic Java Programming Knowledge: Familiarity with basic Java programming concepts such as data types, variables, operators, loops, conditional statements, and methods is essential to build a Number Guessing Game in Java. If you are new to Java, it’s recommended to have some prior experience with programming fundamentals in any other language.

4. Random Number Generation: This program will not require any special libraries other than the Math.random() function. This function will allow the program to generate a random number that the user will have to guess.

5. User Input and Output: You should be comfortable with reading input from the user and displaying output in the console using Java’s standard input/output (I/O) classes, such as Scanner or BufferedReader.

6. Logical Thinking: Building a Number Guessing Game involves designing the logic of the game, including generating a random number, validating user input, and providing hints. Strong logical thinking skills are crucial in building an efficient and effective game.

Source Code

// Java program for the above approach
import java.util.Scanner;

public class GuessGame{

// Function that implements the
// number guessing game
public static void
// Scanner Class
Scanner sc = new Scanner(;

// Generate the numbers
int number = 1 + (int)(100
* Math.random());

// Given K trials
int K = 5;

int i, guess;

"A number is chosen"
+ " between 1 to 100."
+ "Guess the number"
+ " within 5 trials.");

// Iterate over K Trials
for (i = 0; i < K; i++) {

"Guess the number:");

// Take input for guessing
guess = sc.nextInt();

// If the number is guessed
if (number == guess) {
+ " You guessed the number.");
else if (number > guess
&& i != K - 1) {
"The number is "
+ "greater than " + guess);
else if (number < guess
&& i != K - 1) {
"The number is"
+ " less than " + guess);

if (i == K) {
"You have exhausted"
+ " K trials.");

"The number was " + number);

// Driver Code
public static void
main(String arg[])

// Function Call

Explanation of the Code

The program can essentially be broken down into several if-else blocks where the real functionality lies.

1. We started by generating a random number within the range of 1 to 100. We have also specified to the user playing the game the number of tries he/she has.

2. Then, we run a for loop for the number of tries given to the user. In this case, it will be 5 times.

3. The logic used is that If the user can guess the number, we will print out that he has won the game. If the user guesses something wrong, we will give the user a hint in terms of whether the number is greater than or less than the number he has guessed.

4. Finally, If the user is unable to guess the output in 5 tries, we will print out that he has exhausted his tries and has to play again.


Number Guessing Game In Java


This tutorial was a simple number guessing game using Java. There is potential to make an actual game out of this code by adding Swing to create a GUI. If you liked this tutorial, make sure to check out our other projects! Below we have listed a few recommendations for you to follow.

  • Define the Game Logic: Decide on the rules of your number guessing game, such as the range of numbers to guess from, the maximum number of attempts allowed, and the winning condition. Define variables and data structures to keep track of the game state, such as the target number to guess, the current number of attempts, and the player’s guesses.
  • Implement User Input: Use Java’s built-in classes like ‘Scanner’ to take user input for guessing the numbers. Validate and sanitize user input to ensure it meets the game’s requirements, such as being within the valid range of numbers.
  • Generate Random Number: Use Java’s class ‘Random’ to generate a random number within the specified range for the player to guess. Set this as the target number for the game.
  • Implement Game Loop: Create a loop that allows the player to make guesses until the game ends. Use conditional statements to check if the guess is correct or not, and provide feedback to the player accordingly. Keep track of the number of attempts and update the game state accordingly.
  • Implement Game Over Conditions: Define conditions for the game to end, such as when the player guesses the correct number, exceeds the maximum number of attempts, or chooses to quit the game. Display appropriate messages to inform the player of the game outcome.
  • Add Optional Features: You can enhance your game by adding additional features such as difficulty levels, scoring system, hints, or graphical user interface (GUI) using Java’s Swing or JavaFX libraries.
  • Test Your Game: Test your game with various inputs and scenarios to ensure it functions correctly and handles different edge cases. Debug and fix any issues that arise during testing.
  • Document Your Code: Add comments to your code to explain the logic, functionality, and any complex sections. Properly document your code to make it easy for others (and yourself) to understand and maintain it.
  • Refactor and Optimize: Review your code and optimize it for efficiency and readability. Look for opportunities to refactor your code, eliminate redundant or unnecessary operations, and improve the performance of your game.
  • Polish Your Game: Add any finishing touches, such as game titles, welcome messages, error handling, and any other enhancements to make your game more enjoyable and user-friendly.


More Java Projects>>>

You May Also Like To Create…


Submit a Comment

Your email address will not be published. Required fields are marked *