Java Math random () -menetelmä palauttaa arvon, joka on suurempi tai yhtä suuri kuin 0,0 ja alle 1,0.
Menetelmän syntaksi random()
on:
Math.random()
Huomaa : random()
Menetelmä on staattinen menetelmä. Siksi voimme kutsua menetelmää suoraan luokan nimellä Math
.
random () -parametrit
Math.random()
Menetelmä ei ota parametreja.
satunnainen () palautusarvot
- palauttaa näennäissatunnaisen arvo välillä 0,0 ja 1,0
Huomaa : Palautetut arvot eivät ole todella satunnaisia. Sen sijaan arvot syntyy tietyllä laskennallisella prosessilla, jotka täyttävät jonkin satunnaisuuden ehdon. Siksi kutsutaan näennäissatunnaisarvoja.
Esimerkki 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 ) )
Edellä olevassa esimerkissä voimme nähdä, että random () -menetelmä palauttaa kolme erilaista arvoa.
Esimerkki 2: Luo satunnaisluku välillä 10 ja 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 + ", "); ) ) )
Tuotos
Satunnaisluvut välillä 10 ja 20: 15, 13, 11, 17, 20, 11, 17, 20, 14, 14,
Esimerkki 3: Käytä satunnaisia taulukkoelementtejä
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) + ", "); ) ) )
Tuotos
Satunnaiset taulukkoelementit: 67, 34, 77, 34, 12, 77,
Suositellut oppaat
- Math.round ()
- Math.pow ()
- Math.sqrt ()