logo

Mètode Java Math.random().

El java.lang.Math.random() s'utilitza per retornar un nombre de tipus doble pseudoaleatori superior o igual a 0,0 i inferior a 1,0. El nombre aleatori predeterminat sempre es genera entre 0 i 1.

Si voleu un interval específic de valors, heu de multiplicar el valor retornat per la magnitud de l'interval. Per exemple, si voleu obtenir el nombre aleatori entre 0 i 20, l'adreça resultant s'ha de multiplicar per 20 per obtenir el resultat desitjat.

Sintaxi

 public static double random( ) 

Tornar

 It returns a pseudorandom double value greater than or equal to 0.0 and less than 1.0. 

Exemple 1

 public class RandomExample1 { public static void main(String[] args) { // generate random number double a = Math.random(); double b = Math.random(); // Output is different every time this code is executed System.out.println(a); System.out.println(b); } } 
Prova-ho ara

Sortida:

 0.2594036953954201 0.08875674000436018 

Exemple 2

 public class RandomExample2 { public static void main(String[] args) { // Generate random number between 0 to 20 double a = Math.random() * 20; double b = Math.random() * 20; // Output is different every time this code is executed System.out.println(a); System.out.println(b); } } 
Prova-ho ara

Sortida:

 19.09244621979338 14.762266967495655 

Exemple 3

 public class RandomExample3 { public static void main(String[] args) { // Generate random number between 5 to 30 double a = 5 + (Math.random() * 30); double b = 5 + (Math.random() * 30); // Output is different every time this code is executed System.out.println(a); System.out.println(b); } } 
Prova-ho ara

Sortida:

 21.30953881801222 29.762919341853877