Obtener números aleatorios en Java [duplicar]
Posible Duplicado:
Java: generar un número aleatorio en un rango
Me gustaría obtener un valor aleatorio entre 1 y 50 en Java.
¿Cómo puedo hacer eso con la ayuda de Math.random();
?
¿Cómo encuadernar los valores que Matemáticas.random () devuelve?
2 answers
import java.util.Random;
Random rand = new Random();
int n = rand.nextInt(50) + 1;
//50 is the maximum and the 1 is our minimum
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-19 19:59:27
int max = 50;
int min = 1;
1. Usando Matemáticas.random ()
double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);
Esto le dará un valor de 1 a 50 en caso de int o 1.0 (inclusive) a 50.0 (exclusivo) en caso de doble
¿Por qué?
El método Random () devuelve un valor aleatorio número entre 0.0 y 0.9..., usted multiplícalo por 50, así que límite superior se convierte en 0.0 a 49.999... cuando se agrega 1, se convierte en 1.0 a 50.999..., ahora cuando truncas a int, obtienes 1 a 50. (gracias a @rup en los comentarios). leepoint increíble reseña de ambos enfoques.
2. Usando clase aleatoria en Java.
Random rand = new Random();
int value = rand.nextInt(50);
Esto dará un valor de 0 a 49.
Para 1 a 50: rand.nextInt((max - min) + 1) + min;
Source of some Java Random awesomeness.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-03 22:33:09