Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

java - 用Java获取随机数[重复](Getting random numbers in Java [duplicate])

Possible Duplicate:

(可能重复:)
Java: generating random number in a range

(Java:生成一定范围内的随机数)

I would like to get a random value between 1 to 50 in Java.

(我想在Java中获得1到50之间的随机值。)

How may I do that with the help of Math.random();

(我该如何在Math.random();的帮助下做到这一点Math.random();)

?

(?)

How do I bound the values that Math.random() returns?

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

  ask by Unknown user translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first solution is to use the java.util.Random class:

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

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;

Another solution is using Math.random() :

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

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

or

(要么)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...