Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (10.2k points)
I would like to get a random value from 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?

1 Answer

0 votes
by (46k points)

So, the first answer is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Acquire a number from [0 - 49].

int n = rand.nextInt(50);

// Append 1 to the result to get a number from the required range

// (i.e., [1 - 50]).

n += 1;

Another answer is using Math.random():

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

or you can try

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 26, 2021 in Python by laddulakshana (16.4k points)

Browse Categories

...