Java Math aléatoire ()

La méthode Java Math random () renvoie une valeur supérieure ou égale à 0,0 et inférieure à 1,0.

La syntaxe de la random()méthode est:

 Math.random()

Remarque : la random()méthode est une méthode statique. Par conséquent, nous pouvons appeler la méthode directement en utilisant le nom de la classe Math.

Paramètres random ()

La Math.random()méthode ne prend aucun paramètre.

random () Valeurs de retour

  • renvoie une valeur pseudo-aléatoire comprise entre 0,0 et 1,0

Remarque : les valeurs renvoyées ne sont pas vraiment aléatoires. Au lieu de cela, les valeurs sont générées par un processus de calcul défini, qui satisfait à une condition de caractère aléatoire. D'où les valeurs pseudo-aléatoires.

Exemple 1: Java Math.random ()

 class Main ( public static void main(String() args) ( // Math.random() // first random value System.out.println(Math.random()); // 0.45950063688194265 // second random value System.out.println(Math.random()); // 0.3388581014886102 // third random value System.out.println(Math.random()); // 0.8002849308960158 ) )

Dans l'exemple ci-dessus, nous pouvons voir que la méthode random () renvoie trois valeurs différentes.

Exemple 2: générer un nombre aléatoire entre 10 et 20

 class Main ( public static void main(String() args) ( int upperBound = 20; int lowerBound = 10; // upperBound 20 will also be included int range = (upperBound - lowerBound) + 1; System.out.println("Random Numbers between 10 and 20:"); for (int i = 0; i < 10; i ++) ( // generate random number // (int) convert double value to int // Math.round() generate value between 0.0 and 1.0 int random = (int)(Math.random() * range) + lowerBound; System.out.print(random + ", "); ) ) )

Production

 Nombres aléatoires entre 10 et 20:15, 13, 11, 17, 20, 11, 17, 20, 14, 14,

Exemple 3: Accéder à des éléments de tableau aléatoire

 class Main ( public static void main(String() args) ( // create an array int() array = (34, 12, 44, 9, 67, 77, 98, 111); int lowerBound = 0; int upperBound = array.length; // array.length will excluded int range = upperBound - lowerBound; System.out.println("Random Array Elements:"); // access 5 random array elements for (int i = 0; i <= 5; i ++) ( // get random array index int random = (int)(Math.random() * range) + lowerBound; System.out.print(array(random) + ", "); ) ) )

Production

 Éléments de tableau aléatoire: 67, 34, 77, 34, 12, 77,

Tutoriels recommandés

  • Math.round ()
  • Math.pow ()
  • Math.sqrt ()

Articles intéressants...