logo

Générer des nombres aléatoires en Java

Java propose trois façons de générer des nombres aléatoires à l'aide de certaines méthodes et classes intégrées répertoriées ci-dessous :

    classe java.util.Random Méthode Math.random : peut générer des nombres aléatoires de type double. Classe ThreadLocalRandom

1) java.util.Random

  • Pour utiliser cette classe pour générer des nombres aléatoires, nous devons d'abord créer une instance de cette classe, puis appeler des méthodes telles que nextInt(), nextDouble(), nextLong() etc. en utilisant cette instance.
  • Nous pouvons générer des nombres aléatoires de types entiers, float, double, long, booléens en utilisant cette classe.
  • Nous pouvons transmettre des arguments aux méthodes pour placer une limite supérieure sur la plage des nombres à générer. Par exemple, nextInt(6) générera des nombres compris entre 0 et 5 inclus.

Java






// A Java program to demonstrate random number generation> // using java.util.Random;> import> java.util.Random;> > public> class> generateRandom{> > >public> static> void> main(String args[])> >{> >// create instance of Random class> >Random rand =>new> Random();> > >// Generate random integers in range 0 to 999> >int> rand_int1 = rand.nextInt(>1000>);> >int> rand_int2 = rand.nextInt(>1000>);> > >// Print random integers> >System.out.println(>'Random Integers: '>+rand_int1);> >System.out.println(>'Random Integers: '>+rand_int2);> > >// Generate Random doubles> >double> rand_dub1 = rand.nextDouble();> >double> rand_dub2 = rand.nextDouble();> > >// Print random doubles> >System.out.println(>'Random Doubles: '>+rand_dub1);> >System.out.println(>'Random Doubles: '>+rand_dub2);> >}> }>

>

>

Sortir

Random Integers: 618 Random Integers: 877 Random Doubles: 0.11981638980670772 Random Doubles: 0.7288425427367139>

2) Math.random()

La classe Math contient diverses méthodes pour effectuer diverses opérations numériques telles que le calcul d'exponentiations, de logarithmes, etc. L'une de ces méthodes est random(), 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. Le programme ci-dessous explique comment utiliser cette méthode :

Java




// Java program to demonstrate working of> // Math.random() to generate random numbers> import> java.util.*;> > public> class> generateRandom> {> >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.40748894116045375 Random doubles: 0.006683607229094002>

3) classe java.util.concurrent.ThreadLocalRandom

Cette classe est introduite dans Java 1.7 pour générer des nombres aléatoires de type entiers, doubles, booléens, etc. Le programme ci-dessous explique comment utiliser cette classe pour générer des nombres aléatoires :

Java




// Java program to demonstrate working of ThreadLocalRandom> // to generate random numbers.> import> java.util.concurrent.ThreadLocalRandom;> > public> class> generateRandom> {> >public> static> void> main(String args[])> >{> >// Generate random integers in range 0 to 999> >int> rand_int1 = ThreadLocalRandom.current().nextInt();> >int> rand_int2 = ThreadLocalRandom.current().nextInt();> > >// Print random integers> >System.out.println(>'Random Integers: '> + rand_int1);> >System.out.println(>'Random Integers: '> + rand_int2);> > >// Generate Random doubles> >double> rand_dub1 = ThreadLocalRandom.current().nextDouble();> >double> rand_dub2 = ThreadLocalRandom.current().nextDouble();> > >// Print random doubles> >System.out.println(>'Random Doubles: '> + rand_dub1);> >System.out.println(>'Random Doubles: '> + rand_dub2);> > >// Generate random booleans> >boolean> rand_bool1 = ThreadLocalRandom.current().nextBoolean();> >boolean> rand_bool2 = ThreadLocalRandom.current().nextBoolean();> > >// Print random Booleans> >System.out.println(>'Random Booleans: '> + rand_bool1);> >System.out.println(>'Random Booleans: '> + rand_bool2);> >}> }>

>

>

Sortir

Random Integers: -2106603442 Random Integers: 1894823880 Random Doubles: 0.6161052280172054 Random Doubles: 0.8418944588752132 Random Booleans: false Random Booleans: true>

Pour générer des nombres aléatoires avec des plages spécifiques. Il y a 2 façons différentes de procéder :

  • Utiliser une classe aléatoire
  • Utilisation de la méthode Math.random()

1. Utiliser une classe aléatoire

Voici la formule pour générer des nombres aléatoires avec une plage spécifique, où min et max sont nos limites inférieures et supérieures de nombre.

Rand aléatoire = new Random();
int randomNum = rand.nextInt(max – min + 1) + min;

Java




import> java.io.*;> import> java.util.*;> class> GFG {> >public> static> void> main (String[] args) {> >Random rand =>new> Random();> >int> max=>100>,min=>50>;> >System.out.println(>'Generated numbers are within '>+min+>' to '>+max);> >System.out.println(rand.nextInt(max - min +>1>) + min);> >System.out.println(rand.nextInt(max - min +>1>) + min);> >System.out.println(rand.nextInt(max - min +>1>) + min);> >}> }>

>

>

Sortir

Generated numbers are within 50 to 100 58 87 55>

Complexité temporelle : il a une complexité temporelle de O(1)
Espace auxiliaire : O(1) nécessite un espace constant.

2. Utilisation de la méthode Math.random()

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 :

int randomNum = min + (int)(Math.random() * ((max – min) + 1));

Java




vider le cache npm

/*package whatever //do not write package name here */> import> java.io.*;> import> java.util.*;> class> GFG {> >public> static> void> main (String[] args) {> >int> max=>100>,min=>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 53 99 77>

Complexité temporelle : il a une complexité temporelle de O(1)
Espace auxiliaire : O(1) nécessite un espace constant.