Tutoriel Java

La fonction Random en Java : Exercices corrigés pour maîtriser la génération de nombres aléatoires

La génération de nombres aléatoires est une fonctionnalité essentielle dans de nombreux programmes Java, que ce soit pour des simulations, des jeux ou d’autres applications nécessitant une composante aléatoire. En Java, la classe Random fournit des méthodes pour générer des nombres pseudo-aléatoires. Dans cet article, nous explorerons en détail l’utilisation de la fonction Random en Java à travers une série d’exercices corrigés.

Exercice 1 : Génération d’un nombre aléatoire dans une plage donnée


Écrivez un programme Java qui génère un nombre aléatoire compris entre deux bornes spécifiées par l’utilisateur.

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

public class RandomExercice1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Entrez la borne inférieure : ");
        int min = scanner.nextInt();
        System.out.print("Entrez la borne supérieure : ");
        int max = scanner.nextInt();

        Random random = new Random();
        int randomNumber = random.nextInt(max - min + 1) + min;

        System.out.println("Nombre aléatoire entre " + min + " et " + max + " : " + randomNumber);
    }
}
Exercice 2 : Lancer d’un dé à six faces


Écrivez un programme Java qui simule le lancer d’un dé à six faces et affiche le résultat.

import java.util.Random;

public class RandomExercice2 {
    public static void main(String[] args) {
        Random random = new Random();
        int diceRoll = random.nextInt(6) + 1;
        System.out.println("Le dé affiche : " + diceRoll);
    }
}
Exercice 3 : Tirage aléatoire dans une liste


Écrivez un programme Java qui choisit un élément au hasard dans une liste prédéfinie.

import java.util.Random;

public class RandomExercice3 {
    public static void main(String[] args) {
        String[] options = {"Pierre", "Papier", "Ciseaux"};
        Random random = new Random();
        int index = random.nextInt(options.length);
        String randomOption = options[index];
        System.out.println("Choix aléatoire : " + randomOption);
    }
}

Voici une série d’exercices corrigés portant sur l’utilisation de la fonction Random en Java

Exercice 4 : Génération d’un nombre aléatoire dans une plage donnée


Écrivez un programme Java qui génère un nombre aléatoire compris entre deux bornes spécifiées par l’utilisateur.

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

public class RandomExercise1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Entrez la borne inférieure : ");
        int min = scanner.nextInt();
        System.out.print("Entrez la borne supérieure : ");
        int max = scanner.nextInt();

        Random random = new Random();
        int randomNumber = random.nextInt(max - min + 1) + min;

        System.out.println("Nombre aléatoire entre " + min + " et " + max + " : " + randomNumber);
    }
}
Exercice 5 : Lancer d’un dé à six faces


Écrivez un programme Java qui simule le lancer d’un dé à six faces et affiche le résultat.

import java.util.Random;

public class RandomExercise2 {
    public static void main(String[] args) {
        Random random = new Random();
        int diceRoll = random.nextInt(6) + 1;
        System.out.println("Le dé affiche : " + diceRoll);
    }
}
Exercice 6 : Tirage aléatoire dans une liste


Écrivez un programme Java qui choisit un élément au hasard dans une liste prédéfinie.

import java.util.Random;

public class RandomExercise3 {
    public static void main(String[] args) {
        String[] options = {"Pierre", "Papier", "Ciseaux"};
        Random random = new Random();
        int index = random.nextInt(options.length);
        String randomOption = options[index];
        System.out.println("Choix aléatoire : " + randomOption);
    }
}

Ces exercices couvrent différents aspects de l’utilisation de la fonction Random en Java et vous aideront à vous familiariser avec sa mise en œuvre dans vos propres programmes.

Voici quelques cas complexes d’utilisation de la fonction Random en Java, accompagnés de solutions détaillées :

Cas 1 : Génération de nombres aléatoires uniques dans une plage donnée


Écrivez un programme Java qui génère un ensemble de nombres aléatoires uniques dans une plage donnée, sans répétition.

Solution :

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class RandomComplexCase1 {
    public static void main(String[] args) {
        int min = 1;
        int max = 10;
        int count = 5; // Nombre de nombres aléatoires uniques à générer

        Set<Integer> uniqueNumbers = new HashSet<>();
        Random random = new Random();

        while (uniqueNumbers.size() < count) {
            int randomNumber = random.nextInt(max - min + 1) + min;
            uniqueNumbers.add(randomNumber);
        }

        System.out.println("Nombres aléatoires uniques : " + uniqueNumbers);
    }
}
Cas 2 : Génération d’une séquence aléatoire de caractères avec une longueur variable


Écrivez un programme Java qui génère une séquence aléatoire de caractères avec une longueur variable comprise entre deux valeurs spécifiées.

Solution :

import java.util.Random;

public class RandomComplexCase2 {
    public static void main(String[] args) {
        int minLength = 5;
        int maxLength = 10;

        int length = generateRandomLength(minLength, maxLength);
        String randomString = generateRandomString(length);
        System.out.println("Séquence aléatoire : " + randomString);
    }

    public static int generateRandomLength(int min, int max) {
        Random random = new Random();
        return random.nextInt(max - min + 1) + min;
    }

    public static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder randomString = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(characters.length());
            randomString.append(characters.charAt(randomIndex));
        }

        return randomString.toString();
    }
}

Ces cas complexes démontrent des utilisations avancées de la fonction Random en Java et vous permettront de relever des défis plus sophistiqués lors de vos développements.

Autres articles

Comprendre et Utiliser toString() en Java :...
La méthode toString() en Java est une fonctionnalité fondamentale...
Read more
toString() en Java : Guide complet
Dans le monde de la programmation Java, la méthode toString()...
Read more
Quiz Java pour les Entretiens : Testez...
Les entretiens pour des postes de développeurs Java sont souvent...
Read more

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *