Java ofereix tres maneres de generar números aleatoris mitjançant alguns mètodes i classes integrats, tal com s'enumeren a continuació:
- java.util.Random class Math.random method: pot generar nombres aleatoris de tipus doble. Classe ThreadLocalRandom
1) java.util.Random
- Per utilitzar aquesta classe per generar números aleatoris, primer hem de crear una instància d'aquesta classe i després invocar mètodes com ara nextInt(), nextDouble(), nextLong(), etc. utilitzant aquesta instància.
- Podem generar nombres aleatoris de tipus enters, float, double, long, booleans utilitzant aquesta classe.
- Podem passar arguments als mètodes per col·locar un límit superior a l'interval dels números que s'han de generar. Per exemple, nextInt(6) generarà nombres en l'interval del 0 al 5 ambdós inclosos.
Java
convertir cadena en enter
// A Java program to demonstrate random number generation> // using java.util.Random;> import> java.util.Random;> > public> class> generateRandom{> > >public> static> void> main(String args[])> >{> >// create instance of Random class> >Random rand =>new> Random();> > >// Generate random integers in range 0 to 999> >int> rand_int1 = rand.nextInt(>1000>);> >int> rand_int2 = rand.nextInt(>1000>);> > >// Print random integers> >System.out.println(>'Random Integers: '>+rand_int1);> >System.out.println(>'Random Integers: '>+rand_int2);> > >// Generate Random doubles> >double> rand_dub1 = rand.nextDouble();> >double> rand_dub2 = rand.nextDouble();> > >// Print random doubles> >System.out.println(>'Random Doubles: '>+rand_dub1);> >System.out.println(>'Random Doubles: '>+rand_dub2);> >}> }> |
>
>Sortida
Random Integers: 618 Random Integers: 877 Random Doubles: 0.11981638980670772 Random Doubles: 0.7288425427367139>
2) Math.random()
La classe Math conté diversos mètodes per realitzar diverses operacions numèriques, com ara càlcul d'exponenciació, logaritmes, etc. Un d'aquests mètodes és aleatori(), aquest mètode retorna un valor doble amb un signe positiu, major o igual a 0,0 i menor que 1,0. . Els valors retornats s'escullen pseudoaleatòriament. Aquest mètode només pot generar números aleatoris de tipus Doubles. El programa següent explica com utilitzar aquest mètode:
Java
// Java program to demonstrate working of> // Math.random() to generate random numbers> import> java.util.*;> > public> class> generateRandom> {> >public> static> void> main(String args[])> >{> >// Generating random doubles> >System.out.println(>'Random doubles: '> + Math.random());> >System.out.println(>'Random doubles: '> + Math.random());> >}> }> |
>
>
arquitectura javaSortida
Random doubles: 0.40748894116045375 Random doubles: 0.006683607229094002>
3) classe java.util.concurrent.ThreadLocalRandom
Aquesta classe s'introdueix a Java 1.7 per generar nombres aleatoris de tipus enters, dobles, booleans, etc. El programa següent explica com utilitzar aquesta classe per generar números aleatoris:
Java
// Java program to demonstrate working of ThreadLocalRandom> // to generate random numbers.> import> java.util.concurrent.ThreadLocalRandom;> > public> class> generateRandom> {> >public> static> void> main(String args[])> >{> >// Generate random integers in range 0 to 999> >int> rand_int1 = ThreadLocalRandom.current().nextInt();> >int> rand_int2 = ThreadLocalRandom.current().nextInt();> > >// Print random integers> >System.out.println(>'Random Integers: '> + rand_int1);> >System.out.println(>'Random Integers: '> + rand_int2);> > >// Generate Random doubles> >double> rand_dub1 = ThreadLocalRandom.current().nextDouble();> >double> rand_dub2 = ThreadLocalRandom.current().nextDouble();> > >// Print random doubles> >System.out.println(>'Random Doubles: '> + rand_dub1);> >System.out.println(>'Random Doubles: '> + rand_dub2);> > >// Generate random booleans> >boolean> rand_bool1 = ThreadLocalRandom.current().nextBoolean();> >boolean> rand_bool2 = ThreadLocalRandom.current().nextBoolean();> > >// Print random Booleans> >System.out.println(>'Random Booleans: '> + rand_bool1);> >System.out.println(>'Random Booleans: '> + rand_bool2);> >}> }> |
>
document.queryselector
>Sortida
Random Integers: -2106603442 Random Integers: 1894823880 Random Doubles: 0.6161052280172054 Random Doubles: 0.8418944588752132 Random Booleans: false Random Booleans: true>
Per generar números aleatoris amb intervals específics. Hi ha 2 maneres diferents de fer-ho:
- Ús de classe aleatòria
- Utilitzant el mètode Math.random().
1. Ús de classe aleatòria
Aquí teniu la fórmula per generar un nombre aleatori amb un rang específic, on el mínim i el màxim són el nostre límit inferior i superior de nombre.
Random aleatori = new Random();
int randomNum = rand.nextInt (màx – min + 1) + min;
Java
Madhubala
import> java.io.*;> import> java.util.*;> class> GFG {> >public> static> void> main (String[] args) {> >Random rand =>new> Random();> >int> max=>100>,min=>50>;> >System.out.println(>'Generated numbers are within '>+min+>' to '>+max);> >System.out.println(rand.nextInt(max - min +>1>) + min);> >System.out.println(rand.nextInt(max - min +>1>) + min);> >System.out.println(rand.nextInt(max - min +>1>) + min);> >}> }> |
>
>Sortida
Generated numbers are within 50 to 100 58 87 55>
Complexitat temporal: té una complexitat temporal de O(1)
Espai auxiliar: O(1) requereix espai constant.
2. Utilitzant el mètode Math.random().
Aquí teniu la fórmula per generar un nombre aleatori amb un rang específic, on min i max són el nostre límit inferior i superior de nombre:
int randomNum = min + (int)(Math.random() * ((màx – min) + 1));
Java
/*package whatever //do not write package name here */> import> java.io.*;> import> java.util.*;> class> GFG {> >public> static> void> main (String[] args) {> >int> max=>100>,min=>50>;> >System.out.println(>'Generated numbers are within '>+min+>' to '>+max);> >System.out.println(min + (>int>)(Math.random() * ((max - min) +>1>)));> >System.out.println(min + (>int>)(Math.random() * ((max - min) +>1>)));> >System.out.println(min + (>int>)(Math.random() * ((max - min) +>1>)));> >}> }> |
com recuperar aplicacions ocultes
>
>Sortida
Generated numbers are within 50 to 100 53 99 77>
Complexitat temporal: té una complexitat temporal de O(1)
Espai auxiliar: O(1) requereix espai constant.