logo

Generació de nombres aleatoris en Java

Nombres aleatoris s'utilitzen àmpliament en programació per a simulacions de seguretat de jocs, etc. Hi ha diverses maneres de generar números aleatoris mitjançant mètodes i classes integrats a Java. Els enfocaments més utilitzats s'enumeren a continuació:

  • java.util.Random classe
  • Mètode Math.random() (retorna valors dobles)
  • Classe ThreadLocalRandom (introduïda a Java 7)

Explorem cadascun d'aquests enfocaments un per un amb detall

1. Utilitzant java.util.Random

Amb l'ajuda d'aquesta classe podem generar nombres aleatoris de diferents tipus (int double long boolean, etc.).



Mètodes clau:

codis d'error de Linux
  • nextInt(): Aquest mètode genera un nombre enter aleatori (interval complet inclosos els negatius)
  • nextInt(int bound): Aquest mètode genera un nombre enter aleatori entre 0 (inclòs) i lligat (exclusiu)
  • següentDoble(): Aquest mètode genera un doble aleatori entre 0,0 (inclòs) i 1,0 (exclusiu)
  • nextBoolean(): Veritable o fals a l'atzar

Exemple :

Java
// Generating random number using java.util.Random; import java.util.Random; public class Geeks{    public static void main(String[] args) {    // Creating the instance of Random class  Random r= new Random();  // Generate random integers in range 0 to 999  int r1 = r.nextInt(1000);  int r2 = r.nextInt(1000);  // Printing random integers  System.out.println('Random Integers: ' + r1);  System.out.println('Random Integers: ' + r2);  // Generate random doubles  double rd1 = r.nextDouble();  double rd2 = r.nextDouble();  // Printing random doubles  System.out.println('Random Doubles: ' + rd1);  System.out.println('Random Doubles: ' + rd2);  } } 

Sortida
Random Integers: 39 Random Integers: 190 Random Doubles: 0.4200728082969115 Random Doubles: 0.9327571841228275 

Generació de números en un rang específic

25 de 100

La fórmula per generar un nombre aleatori amb un interval específic es mostra a continuació:

Random aleatori = new Random();

int randomNum = rand.nextInt(max - min + 1) + min;

Nota: min i max són el nostre límit inferior i superior de nombre.

Exemple:

Java
// Generating random number in a specific range  import java.io.*; import java.util.*; class Geeks {    public static void main (String[] args) {  Random r = new Random();  int max=100min=50;  System.out.println('Generated numbers are within '+ min +' to '+ max);  System.out.println(r.nextInt(max - min + 1) + min);  System.out.println(r.nextInt(max - min + 1) + min);  System.out.println(r.nextInt(max - min + 1) + min);  } } 

Sortida
Generated numbers are within 50 to 100 55 51 51 


2. Utilitzant Math.random()

El Classe de matemàtiques conté diversos mètodes per realitzar diverses operacions numèriques, com ara calcular logaritmes d'exponenciació, etc. Un d'aquests mètodes és aleatori () aquest mètode retorna un valor doble amb un signe positiu superior o igual a 0,0 i inferior a 1,0. Els valors retornats s'escullen pseudoaleatòriament. Aquest mètode només pot generar números aleatoris de tipus Doubles.

Exemple:

en cadena en java
Java
// Java program to demonstrate working of  // Math.random() to generate random numbers import java.util.*;   public class Geeks {  public static void main(String args[])  {  // Generating random doubles  System.out.println('Random doubles: ' + Math.random());  System.out.println('Random doubles: ' + Math.random());  } } 

Sortida
Random doubles: 0.38601320746656065 Random doubles: 0.9209882942481417 

Generació de números en un rang específic

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:

llista j

int randomNum = min + (int)(Math.random() * ((màx - min) + 1));

Exemple:

Java
// Demonstrating how to generate random  // number within a specific range import java.io.*; import java.util.*; class Geeks {    public static void main (String[] args) {  int max=100min=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)));   } } 

Sortida
Generated numbers are within 50 to 100 82 68 77 


3. Utilitzant ThreadLocalRandom

Aquesta és la manera recomanada en entorns multifils, ja que redueix la contenció.

Mètodes clau:

  • current().nextInt(): Enter aleatori (interval complet)
  • current().nextInt(min max + 1): Enter aleatori a l'interval (he afegit aquest exemple acotat)
  • current().nextDouble(): Doble aleatori (0,0 a 1,0)
  • current().nextBoolean(): Veritable o fals a l'atzar

Exemple:

Java
// Demonstrates how to generate random integers  // doubles and booleans using ThreadLocalRandom import java.util.concurrent.ThreadLocalRandom; public class Geeks {  public static void main(String[] args) {  // Generate random integers in range 0 to 999  // Random number between 0 and 999  int r1 = ThreadLocalRandom.current().nextInt(1000);    // Random number between 0 and 999  int r2 = ThreadLocalRandom.current().nextInt(1000);   // Print random integers  System.out.println('Random Integers: ' + r1);  System.out.println('Random Integers: ' + r2);  // Generate Random doubles between 0.0 (inclusive)   // and 1.0 (exclusive)  double rd1 = ThreadLocalRandom.current().nextDouble();  double rd2 = ThreadLocalRandom.current().nextDouble();  // Print random doubles  System.out.println('Random Doubles: ' + rd1);  System.out.println('Random Doubles: ' + rd2);  // Generate random booleans  boolean rb1 = ThreadLocalRandom.current().nextBoolean();  boolean rb2 = ThreadLocalRandom.current().nextBoolean();  // Print random Booleans  System.out.println('Random Booleans: ' + rb1);  System.out.println('Random Booleans: ' + rb2);  } } 

Sortida
Random Integers: 812 Random Integers: 461 Random Doubles: 0.7420865203902993 Random Doubles: 0.9580683365617423 Random Booleans: false Random Booleans: false