Java Math random ()

El método random () de Java Math devuelve un valor mayor o igual a 0.0 y menor que 1.0.

La sintaxis del random()método es:

 Math.random()

Nota : el random()método es un método estático. Por lo tanto, podemos llamar al método directamente usando el nombre de la clase Math.

Parámetros aleatorios ()

El Math.random()método no toma ningún parámetro.

valores de retorno aleatorios ()

  • devuelve un valor pseudoaleatorio entre 0.0 y 1.0

Nota : Los valores devueltos no son realmente aleatorios. En cambio, los valores se generan mediante un proceso computacional definido, que satisface alguna condición de aleatoriedad. Por eso se denominan valores pseudoaleatorios.

Ejemplo 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 ) )

En el ejemplo anterior, podemos ver que el método random () devuelve tres valores diferentes.

Ejemplo 2: generar un número aleatorio entre 10 y 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 + ", "); ) ) )

Salida

 Números aleatorios entre 10 y 20: 15, 13, 11, 17, 20, 11, 17, 20, 14, 14,

Ejemplo 3: acceder a elementos de matriz aleatoria

 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) + ", "); ) ) )

Salida

 Elementos de matriz aleatoria: 67, 34, 77, 34, 12, 77,

Tutoriales recomendados

  • Math.round ()
  • Math.pow ()
  • Math.sqrt ()

Articulos interesantes...