Guess the Number Game in Java

In guess the number game, the computer program will come up with a random number within a range (for example, 1 to 1000). The player (user) is asked to guess this number. If the guessed number is bigger than the actual number, the computer will respond with the message "too high". If the guessed number is smaller than the actual number, computer will respond with the message "too low". This process repeats until the number is found. The aim of the game is to find the secret number in minimum number of guesses. At the end of the game the number and the number of guesses are revealed.

Guess the number game is used to illustrate basic principles of programming. It demonstrates use of user input, conditional checking and loop constructs. It also demonstrates use of random number generation.

The following example program shows how guess the number game can be written in Java. It also demonstrates proper use of Java functions where each function is responsible for a specific feature of the program. This refactoring of the program into multiple functions is the key to highly maintainable and readable programs.

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;

public class GuessNumberGame {
    // Guess limits
    private static final int MIN_NUMBER = 1;
    private static final int MAX_NUMBER = 1000;
    public static void main(String[] args) {
        GuessNumberGame game = new GuessNumberGame();
     * Play the guess number game.
    public void startGame() {
        boolean isUserGuessCorrect = false;
        int numberOfGuesses = 0;
        // computer thinks a number
        int computerNumber = getNumberByComputer();
        // Program continues till user guesses the number correctly
        while(!isUserGuessCorrect) {
            int userNumber = getUserGuessedNumber();
            if(userNumber > computerNumber) {
                System.out.println("Sorry, the number you guessed is too high");
            }else if(userNumber < computerNumber) {
                System.out.println("Sorry, the number you guessed is too low");
            }else if(userNumber == computerNumber) {
                System.out.println("Congratulations! Your guess is correct!");
                isUserGuessCorrect = true;
        System.out.println("You found the number in "+numberOfGuesses+" guesses");
     * Returns a random number between 1 and 1000 inclusive.
     * @return 
    public int getNumberByComputer() {
        return ThreadLocalRandom.current().nextInt(MIN_NUMBER, MAX_NUMBER+1);
     * Returns the number guessed by user
     * @return 
    public int getUserGuessedNumber() {
        Scanner sn = new Scanner(;
        System.out.println("Please guess the number: ");
        return sn.nextInt();

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.

Leave a Reply