Project: Guess the number

Updated: 3 years ago

Check out other lessons in Learning the Java syntax

Now that we know how to create variables and arrays, conditionals, loops and gather input from the user, it's time to create a proper Java application. We are going to create a game called Guess the number.

The rules for the game Guess the number are pretty straightforward. You will generate a random number and then ask the user for that number. If the user's guess is below the generated number, you display "Aim higher, the number is too low", if it's above the generated number, you display "Aim lower, the number is too high". If the user guesses the generated number, you display "Bingo, you got it!".

In pseudocode this will be a bit like this:

  1. Generate a random number.
  2. Ask the user for a number.
  3. If the number is lower, display "Aim higher...".
  4. If the number is higher, display "Aim lower...".
  5. If the number is correct, display "Bingo!".
  6. Go to step 2 until the user gueses the number.

Generating a random number

I'll show you a quick way of generating a random number.

package com.codescrubs;

// We need to tell the compiler from where to import the Random class
import java.util.Random;

public class Main
{
    public static void main(String[] args) 
    {
        // Random class is used to generate random values
        Random random = new Random();

        // We use nextInt(101) to create a random number between 0 and 100
        int randomNumber = random.nextInt(101); 

        System.out.println(randomNumber);
    }
}

The random class is used for generating random values and we'll use it to generate a random int. If you put a number between the parenthesis, it will generate a random number between a zero (inclusive) and the passed number (exclusive). That means if we put a number 101 in there, we'll get a random number between 0 and a 100. Don't forget to write import java.util.Random; at the top so that the compiler knows where to find the Random class.

Get to work! Create you very own Guess the number game. If you get stuck, check my implementation of the game below.

package com.codescrubs;

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

public class Main
{

    public static void main(String[] args)
    {
            //  Let's generate a random number between 0 and 100
            Random random = new Random();
            int randomNumber = random.nextInt(101);

            //  Setup the world
            int guessedNumber = -1;

            //  Let's create our scanner object that will be used
            //  to get the user's input
            Scanner scanner = new Scanner(System.in);

            //  Let's repeat the cycle as long as the player has 
            //  failed to guess the number
            while(guessedNumber != randomNumber)
            {

            //  Making sure that our program doesn't break when the user 
            //  inputs a invalid input
            try
            {
                System.out.println("Input a whole number between 0 and 100.");

                //  Read the number
                guessedNumber = scanner.nextInt();
                //  Clear the queue and remove the remaining enter keypress
                scanner.nextLine();

                //  Give hints to the user
                if(guessedNumber < randomNumber)
                {
                    System.out.println(guessedNumber + " is too low. Aim higher");
                }
                else if (guessedNumber > randomNumber)
                {
                    System.out.println(guessedNumber + " is too high. Aim lower");
                }
            }
            catch (InputMismatchException exception)
            {
                //  Help the player out by describing the error.
                System.out.println("This is not a valid number. Please input a whole number");

                //  Let's clear what ever the user has typed in
                scanner.nextLine();
            }
        }

        //  Woop woop, the player has won.
        System.out.println("Bingo! You have won!");
    }
}

Bonus

  1. Ask the player on the type of game they want to play. An easy game has unlimited gueses, a hard game has only 6 gueses.
  2. Ask the player how big the random generated number can be.
  3. Count the number of guesses and display the end result to the player.
  4. Reverse the roles. The player inputs a number and the computer has to guess it (either randomly, or by using a guessing algorithm you make up yourself).
« Previous lesson:
Exceptions