logo

Metoda Java Math.random().

The java.lang.Math.random() se používá k vrácení pseudonáhodného čísla dvojitého typu většího nebo rovného 0,0 a menšího než 1,0. Výchozí náhodné číslo se vždy generuje mezi 0 a 1.

Pokud chcete určit konkrétní rozsah hodnot, musíte vrácenou hodnotu vynásobit velikostí rozsahu. Například, pokud chcete získat náhodné číslo mezi 0 až 20, výsledná adresa musí být vynásobena 20, abyste získali požadovaný výsledek.

Syntax

 public static double random( ) 

Vrátit se

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

Příklad 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); } } 
Otestujte to hned

Výstup:

 0.2594036953954201 0.08875674000436018 

Příklad 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); } } 
Otestujte to hned

Výstup:

 19.09244621979338 14.762266967495655 

Příklad 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); } } 
Otestujte to hned

Výstup:

 21.30953881801222 29.762919341853877