Getting random numbers in Java [duplicate]

2019-01-03 03:42发布

Possible Duplicate:
Java: generating random number in a range

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?

标签: java random prng
2条回答
▲ chillily
2楼-- · 2019-01-03 04:10

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;

or

int random = (int)(Math.random() * 50 + 1);
查看更多
放荡不羁爱自由
3楼-- · 2019-01-03 04:32
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.

查看更多
登录 后发表回答