Guessing numbers

exercise No. 84


Write a simple game asking a user to guess a randomly chosen number.

Your program will select an integer (pseudo) random number between zero and an exclusive configurable fixed upper limit e.g. 10. The user will have a configurable number of tries to guess the number in question. Each time after entering a number your program will respond with either of the following:

Congratulations, you won!

You won!

You lost!

Game over, try another run?

Game continues, either of:
  • Number is too low

  • Number is too high

The system offers a maximum number of tries e.g. 6. In the following example the system initially selected the secret number 5. A possible dialogue looks like:

Try to guess my secret number between 0 and 10:
You have 5 attempts
Input your guess:4
Value is too low
Input your guess:6
Value is too high
Input your guess:5
Congratulations, you won!

Regarding reading user input and creating random numbers please use the following recipe to get started:

package ...

import java.util.Random;
   public static void main(String[] args) {

       // Add some parameter here e.g. range of number to be guessed,
       // and number of tries.

      final int randomValue =  new Random() // Selecting a pseudo random value
            .nextInt(11);                   // between 0 and 10 (inclusive).

      // ToDo: complete the implementation


final int maxValueInclusive = 10, // Guessing a value from 0 to this value (inclusive)
          numOfUserAttempts = 5,  // User will have this number of tries guessing the random value.
                randomValue =     // Create a random value between 0
     new Random().nextInt(        // and maxValueInclusive.
     maxValueInclusive + 1);

System.out.println("Try to guess my secret number in between 0 and "
                     + maxValueInclusive + ":");

System.out.println("You have " + numOfUserAttempts + " attempts");

try (final Scanner scan = new Scanner( {
    boolean numberWasFound = false;

    for (int i = 0; i < numOfUserAttempts; i++) {
        System.out.print("Input your guess:");
        final int userGuess = scan.nextInt();
        if (userGuess < randomValue) {
            System.out.println("Number is too low");
        } else if (randomValue < userGuess) {
            System.out.println("Number is too high");
        } else {
            numberWasFound = true;
    if (numberWasFound) {
        System.out.println("Congratulations, you won!");
    } else {
        System.out.println("Game over, try another run?");

In case you don't like break statements the following variant also solves the problem:

boolean numberWasFound = false;

for (int i = 0; !numberWasFound && i < numOfUserAttempts; i++) {
    } else {
        numberWasFound = true;
        // No »break« statement required anymore