Metoda random () Java Math vrací hodnotu, která je větší nebo rovna 0,0 a menší než 1,0.
Syntaxe random()
metody je:
Math.random()
Poznámka : random()
Metoda je statická. Proto můžeme metodu volat přímo pomocí názvu třídy Math
.
random () parametry
Math.random()
Metoda nebere žádné parametry.
random () Návratové hodnoty
- vrací pseudonáhodnou hodnotu mezi 0,0 a 1,0
Poznámka : Vrácené hodnoty nejsou skutečně náhodné. Namísto toho jsou hodnoty generovány určitým výpočetním procesem, který splňuje určitou podmínku náhodnosti. Proto se nazývají pseudonáhodné hodnoty.
Příklad 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 ) )
Ve výše uvedeném příkladu vidíme, že metoda random () vrací tři různé hodnoty.
Příklad 2: Generování náhodných čísel mezi 10 a 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 + ", "); ) ) )
Výstup
Náhodná čísla mezi 10 a 20: 15, 13, 11, 17, 20, 11, 17, 20, 14, 14,
Příklad 3: Přístup k prvkům náhodného pole
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) + ", "); ) ) )
Výstup
Náhodné pole: 67, 34, 77, 34, 12, 77,
Doporučené výukové programy
- Math.round ()
- Math.pow ()
- Math.sqrt ()