本文介绍了在 Java 中获取随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Java 中获得 1 到 50 之间的随机值.
I would like to get a random value between 1 to 50 in Java.
如何在 Math.random();
的帮助下做到这一点?
How may I do that with the help of Math.random();
?
如何绑定 Math.random()
返回的值?
How do I bound the values that Math.random()
returns?
推荐答案
第一个解决方案是使用 java.util.Random
类:
The first solution is to use the java.util.Random
class:
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()
:
Another solution is using Math.random()
:
double random = Math.random() * 49 + 1;
或
int random = (int)(Math.random() * 50 + 1);
这篇关于在 Java 中获取随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!