Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
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
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...