Java Math random () metode atgriež vērtību, kas ir lielāka vai vienāda ar 0,0 un mazāka par 1,0.
Metodes sintakse random()
ir šāda:
Math.random()
Piezīme . random()
Metode ir statiska. Tādējādi mēs varam izsaukt metodi tieši, izmantojot klases nosaukumu Math
.
izlases () parametri
Math.random()
Metode neveic nekādus parametrus.
izlases () atgriešanās vērtības
- atgriež pseidorandom vērtību starp 0,0 un 1,0
Piezīme . Atgrieztās vērtības nav patiesi nejaušas. Tā vietā vērtības ģenerē noteikts skaitļošanas process, kas apmierina dažus nejaušības nosacījumus. Līdz ar to sauc par pseidorandom vērtībām.
1. piemērs: 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 ) )
Iepriekš minētajā piemērā mēs varam redzēt, ka random () metode atgriež trīs dažādas vērtības.
2. piemērs. Izveidojiet nejaušu skaitli no 10 līdz 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 + ", "); ) ) )
Rezultāts
Nejaušie skaitļi no 10 līdz 20: 15, 13, 11, 17, 20, 11, 17, 20, 14, 14,
3. piemērs: Piekļuve izlases masīva elementiem
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) + ", "); ) ) )
Rezultāts
Izlases masīva elementi: 67, 34, 77, 34, 12, 77,
Ieteicamās konsultācijas
- Math.round ()
- Math.pow ()
- Math.sqrt ()