Nombres aléatoires sont largement utilisés dans la programmation pour les simulations de sécurité des jeux, etc. Il existe plusieurs façons de générer des nombres aléatoires à l'aide de méthodes et de classes intégrées à Java. Les approches les plus couramment utilisées sont répertoriées ci-dessous :
- classe java.util.Random
- Méthode Math.random() (renvoie des valeurs doubles)
- Classe ThreadLocalRandom (introduite dans Java 7)
Explorons chacune de ces approches une par une en détail
1. Utilisation de java.util.Random
Avec l'aide de cette classe, nous pouvons générer des nombres aléatoires de différents types (int double long boolean etc.).
Méthodes clés :
- suivantInt() : Cette méthode génère un entier aléatoire (plage complète incluant les négatifs)
- nextInt (int lié): Cette méthode génère un entier aléatoire compris entre 0 (inclus) et lié (exclusif)
- suivantDouble() : Cette méthode génère un double aléatoire entre 0,0 (inclus) et 1,0 (exclusif)
- nextBoolean() : Aléatoire vrai ou faux
Exemple :
Java// Generating random number using java.util.Random; import java.util.Random; public class Geeks{ public static void main(String[] args) { // Creating the instance of Random class Random r= new Random(); // Generate random integers in range 0 to 999 int r1 = r.nextInt(1000); int r2 = r.nextInt(1000); // Printing random integers System.out.println('Random Integers: ' + r1); System.out.println('Random Integers: ' + r2); // Generate random doubles double rd1 = r.nextDouble(); double rd2 = r.nextDouble(); // Printing random doubles System.out.println('Random Doubles: ' + rd1); System.out.println('Random Doubles: ' + rd2); } }
Sortir
Random Integers: 39 Random Integers: 190 Random Doubles: 0.4200728082969115 Random Doubles: 0.9327571841228275
Générer des nombres dans une plage spécifique
La formule pour générer un nombre aléatoire avec une plage spécifique est répertoriée ci-dessous :
Rand aléatoire = new Random();
int randomNum = rand.nextInt(max - min + 1) + min;
Note: min et max sont nos limites inférieures et supérieures de nombre.
Exemple:
nombre aléatoire entre 1 et 10Java
// Generating random number in a specific range import java.io.*; import java.util.*; class Geeks { public static void main (String[] args) { Random r = new Random(); int max=100min=50; System.out.println('Generated numbers are within '+ min +' to '+ max); System.out.println(r.nextInt(max - min + 1) + min); System.out.println(r.nextInt(max - min + 1) + min); System.out.println(r.nextInt(max - min + 1) + min); } }
Sortir
Generated numbers are within 50 to 100 55 51 51
2. Utilisation de Math.random()
Le Cours de mathématiques contient diverses méthodes pour effectuer diverses opérations numériques telles que le calcul de logarithmes d'exponentiation, etc. L'une de ces méthodes est aléatoire() cette méthode renvoie une valeur double avec un signe positif supérieur ou égal à 0,0 et inférieur à 1,0. Les valeurs renvoyées sont choisies pseudo-aléatoirement. Cette méthode ne peut générer que des nombres aléatoires de type Doubles.
Exemple:
Java// Java program to demonstrate working of // Math.random() to generate random numbers import java.util.*; public class Geeks { public static void main(String args[]) { // Generating random doubles System.out.println('Random doubles: ' + Math.random()); System.out.println('Random doubles: ' + Math.random()); } }
Sortir
Random doubles: 0.38601320746656065 Random doubles: 0.9209882942481417
Générer des nombres dans une plage spécifique
Voici la formule pour générer un nombre aléatoire avec une plage spécifique où min et max sont nos limites inférieure et supérieure de nombre :
acteur bélier
int randomNum = min + (int)(Math.random() * ((max - min) + 1));
Exemple:
Java// Demonstrating how to generate random // number within a specific range import java.io.*; import java.util.*; class Geeks { public static void main (String[] args) { int max=100min=50; System.out.println('Generated numbers are within '+min+' to '+max); System.out.println(min + (int)(Math.random() * ((max - min) + 1))); System.out.println(min + (int)(Math.random() * ((max - min) + 1))); System.out.println(min + (int)(Math.random() * ((max - min) + 1))); } }
Sortir
Generated numbers are within 50 to 100 82 68 77
3. Utilisation de ThreadLocalRandom
Il s'agit de la méthode recommandée dans les environnements multithread car elle réduit les conflits.
Méthodes clés :
- courant().nextInt() : Entier aléatoire (gamme complète)
- courant().nextInt(min max + 1) : Entier aléatoire dans la plage (j'ai ajouté cet exemple limité)
- courant().nextDouble() : Double aléatoire (0,0 à 1,0)
- courant().nextBoolean() : Aléatoire vrai ou faux
Exemple:
Java// Demonstrates how to generate random integers // doubles and booleans using ThreadLocalRandom import java.util.concurrent.ThreadLocalRandom; public class Geeks { public static void main(String[] args) { // Generate random integers in range 0 to 999 // Random number between 0 and 999 int r1 = ThreadLocalRandom.current().nextInt(1000); // Random number between 0 and 999 int r2 = ThreadLocalRandom.current().nextInt(1000); // Print random integers System.out.println('Random Integers: ' + r1); System.out.println('Random Integers: ' + r2); // Generate Random doubles between 0.0 (inclusive) // and 1.0 (exclusive) double rd1 = ThreadLocalRandom.current().nextDouble(); double rd2 = ThreadLocalRandom.current().nextDouble(); // Print random doubles System.out.println('Random Doubles: ' + rd1); System.out.println('Random Doubles: ' + rd2); // Generate random booleans boolean rb1 = ThreadLocalRandom.current().nextBoolean(); boolean rb2 = ThreadLocalRandom.current().nextBoolean(); // Print random Booleans System.out.println('Random Booleans: ' + rb1); System.out.println('Random Booleans: ' + rb2); } }
Sortir
Random Integers: 812 Random Integers: 461 Random Doubles: 0.7420865203902993 Random Doubles: 0.9580683365617423 Random Booleans: false Random Booleans: false