Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in

Sequence

Guess the number

Core exercise

The computer picks an integer in [1, 100]. The player suggests numbers until they find it. At each attempt, the program prints “trop grand” (too big), “trop petit” (too small) or “bravo” (well done).

Goals: Randomness (Random), loops, comparisons, messages.

Features

  • indice(int proposition, int secret) returns exactly "trop grand", "trop petit" or "bravo".
  • jouer(Scanner sc, int secret) loops until the right answer and returns the number of attempts.
  • The number of attempts is printed at the end.

Steps

  1. tirerNombreSecret(int min, int max) → an int with Random.
  2. indice(proposition, secret) → the comparison, isolated and therefore testable.
  3. jouer(sc, secret) → the main loop, which counts the moves.

Criteria: Input validation (no crash if the user types text), clear feedback, counting the moves.

A workshop goes here: you write and run code in it. It requires JavaScript.

Starting code

NombreMystere.java

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

public class NombreMystere {

    public static int tirerNombreSecret(int min, int max) {
        // TODO : un entier au hasard entre min et max inclus
        return min;
    }

    public static String indice(int proposition, int secret) {
        // TODO : "trop grand", "trop petit" ou "bravo"
        return "";
    }

    public static int jouer(Scanner sc, int secret) {
        // TODO : boucler tant que ce n'est pas trouve, renvoyer le nombre d'essais
        return 0;
    }
}

Exercices.java

import java.util.Scanner;

public class Exercices {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int secret = NombreMystere.tirerNombreSecret(1, 100);
        int essais = NombreMystere.jouer(sc, secret);
        System.out.println("Trouve en " + essais + " essai(s)");
        sc.close();
    }
}

The core exercise is validated in the workshop, which requires JavaScript.

Hint 1

new Random().nextInt(max - min + 1) + min draws an integer in [min, max]. Isolating indice() from the rest makes it possible to test it without depending on chance: that is exactly what the checks below do.

Extensions

  • A limit on attempts (for example 7) and a losing message.
  • “Hot / cold” mode: say whether the player is getting closer.