java中随机数的获取

Getting random numbers in Java

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Java: generating random number in a range

我想得到一个随机值在1到50在爪哇。

我怎样才能在Math.random();的帮助下做到这一点?

如何绑定math.random()返回的值?


第一种解决方案是使用java.util.Random类:

1
2
3
4
5
6
7
8
9
10
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;

另一种解决方案是使用Math.random()

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

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


1
2
int max = 50;
int min = 1;

1。使用math.random()。

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

如果是int,这个值将从1到50或1.0(含)至50.0(不含),如果是双份

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。在Java中使用随机类。

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

这将给出0到49之间的值。

对于1到50:rand.nextInt((max - min) + 1) + min;

一些Java随机源的惊人之处。