Number Guessing Game in Java with Source Code

In this post, I will be sharing the number guessing game in java with source code. As the name suggests, the player needs to guess the number between two given numbers. This game is played between 2 or more players. In this number guessing game, the computer will pick the SECRET number and the player who should find this SECRET number within a given number of tries. Let's understand the rules of the game first before moving on to the algorithm and java program.

Read Also: Hangman Game in Java

Rules of the Number Guessing Game

1. The computer randomly selects the SECRET number within the defined range of numbers, here 1 to 100, and prompts the player to guess the number.

2. In this program, we ask the player to enter any number between 1 to 100. The player enters any random number within the defined range. We call it as inputNumber.

3. If the player number i.e inputNumber is same as the SECRET number then the game stops, otherwise,

3.a. If the player number is lesser than the SECRET number then, the range of the number to choose from will be changed,  that is now the player has to select a number between inputNumber to 100.

3.b. If the player inputNumber is greater than the SECRET number then,
the range of the numbers to select an input from for player will be reduced from 1 to inputNumber.

4. The game continues till the player guesses the correct number within a given number of tries.

Number Guessing Game in Java Program Code:

import java.util.Scanner;


/****************************************************** /
** Program: GuessingNumberGame.java**
** Author:  **
** Date:    20 April 2013
/******************************************************/
public class GuessingNumberGame {
    
    /**
    * @Range defined below
    */
    static int low=1,high=100;
    static int numberOfTurnsLeft = 5; 
 
    public static void main(String[] args) {
        gameBegins();
    }
    public static void gameBegins()
    {
        int secretNumber=0;
        
        double i =Math.random();
        if(i != 0)
        secretNumber= (int) (i*101);
        else
        {
            gameBegins();
            System.out.println("Please enter a valid number");
        }
        System.out.println("");
        System.out.println("-------------------------");
        System.out.println("NEW GAME ");
        System.out.println("-------------------------");
        System.out.println("");
        System.out.println("");
        System.out.println("pick a number between 1-100! You will get 5 turns");
        
        while(true)
        {
            int inputNumber = playerInput();
            predictionResult(inputNumber, secretNumber);
        }
    }
    
    
    public static int playerInput()
    {
        Scanner in = new Scanner(System.in);
        int playerInput= in.nextInt();
        System.out.println("player guesses "+ playerInput);
        return playerInput;
    }
    
    public static void predictionResult(int inputNumber , int secretNumber)
    {
        /* Check if inputNumber is lesser
        than secretNumber */
        if(inputNumber < secretNumber)
        {
            low=inputNumber;
            System.out.println(" Sorry,that is too low ");
            low=low+1;
            numberOfTurnsLeft = numberOfTurnsLeft-1;
            if (numberOfTurnsLeft == 0) {
                System.out.println("YOU LOSE! The SECRET number was "+ secretNumber); 
                playAgain();
            }    
            System.out.println("pick a number between "+low +"-"+high + " and turns left "+ numberOfTurnsLeft);
        }
        /* Check if inputNumber is higher
        than secretNumber */        
        else if(inputNumber > secretNumber)
        {
            high=inputNumber;
            System.out.println(" Sorry,that number is  too high ");
            high=high-1;
            numberOfTurnsLeft = numberOfTurnsLeft-1;
            if (numberOfTurnsLeft == 0) {
                System.out.println("YOU LOSE! The SECRET number was "+ secretNumber); 
                playAgain();
            }
            System.out.println("pick a number between "+low +"-"+high + " and turns left "+ numberOfTurnsLeft);
        }
        else
        {
            System.out.println("YOU WIN! The SECRET number was "+ secretNumber);
            playAgain();
        }
    }
    public static void playAgain()
    {
        low=1;
        high=100;
        numberOfTurnsLeft = 5;
        gameBegins();
        
    }
    
}

Output:
number guessing game in java























Algorithm:

1. The computer randomly selects one secret number. It prompts the player to guess it correctly in the minimum number of attempts within a defined range here 1 to 100.

2. Player inputs any number within the defined range.

3. If
    inputNumber is greater than the secret number than range reduces to 1 to inputNumber
    else
    range reduces to inputNumber to 100

4. Repeat steps from 2 again.

Here we make sure that the game starts again once it is finished. You can also make it an automated program, that is the computer will set the SECRET number and then computer only will try to find it. For that, you just need to use a random method again and compare it with the target or secret number.

That's all for today. Please mention in comments in case you have any questions related to the number guessing game in java with source code.

You may also like:

Rock Paper Scissor game in java (answer)
Hangman game in java (solution)
Snakes and Ladders game in java (answer)
Tic tac toe gui based game in java (solution)
Tic tac toe console game in java (solution)

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry