Getting random numbers in Java [duplicate]

orellabair 105 25th Jan, 2019

                         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?

The first solution is Using java.util.Random class:

import java.util.Random;

Random rand = new Random();

int n = rand.nextInt(50) + 1;
//50 is the maximum and the 1 is our minimum.
Another solution is using Math.random()

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

int random = (int)(Math.random() * 50 + 1);
To share this paste, please copy this url and send to your friends.
RAW Paste Data