Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting random numbers in Java [duplicate]

Tags:

java

random

I would like to get a random value between 1 to 50 in Java.

How may I do that with the help of Math.random();?

How do I bound the values that Math.random() returns?

like image 640
Unknown user Avatar asked May 04 '11 17:05

Unknown user


People also ask

How do you repeat random numbers in Java?

Random num = new Random(); Now, in a loop, use the nextInt() method since it is used to get the next random integer value. You can also set a range, like for 0 to 20, write it as. nextInt( 20 );

How do you generate a random double in Java?

In order to generate Random double type numbers in Java, we use the nextDouble() method of the java. util. Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.


2 Answers

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);
like image 146
nyanev Avatar answered Sep 27 '22 11:09

nyanev


int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

like image 43
zengr Avatar answered Sep 27 '22 11:09

zengr