-4

Possible Duplicate:
Java: generating random number in a range

I am using Math.random() in java. But always it returns less than 0. Such as 0.4454590405954

Is there a way to return meaningful numbers as what i want.

For example i want to return numbers which values are 0 to 100. How i can do it?

4

2 回答 2

2

You can use Random.nextInt(int n) object to return int 0 - 100

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

For example

Random random = new Random();
int myRandom = random.nextInt(101);
// do magic
于 2012-04-19T16:11:21.067 回答
2

使用以下命令获取 0 到 100 之间的整数:

Random r = new Random();
int x = r.nextInt(101); // from 0 (inclusive) to 101 (exclusive)
于 2012-04-19T16:13:06.207 回答