好吧,我对 Java 还很陌生。我们接到一项任务,要创建一个游戏,您必须猜测计算机生成的随机整数。问题是我们的讲师坚持要我们使用:
double randNumber = Math.random();
然后将其转换为接受 1 - 100(含)的随机整数。我有点不知所措。到目前为止我所拥有的是:
//Create random number 0 - 99
double randNumber = Math.random();
d = randNumber * 100;
//Type cast double to int
int randomInt = (int)d;
然而,随机双倍的随机问题挥之不去的是,0是可能的,而100则不是。我想改变它,使 0 不再是可能的答案,而 100 是可能的。帮助?
或
Random r = new Random();
int randomInt = r.nextInt(100) + 1;
你就快到了。只需将结果加 1 即可:
int randomInt = (int)d + 1;
这会将您的范围“转移”至
1 - 100
而不是 0 - 99
。
ThreadLocalRandom
类提供了int nextInt(int origin, int bound)
方法来获取范围内的随机整数:
// Returns a random int between 1 (inclusive) & 101 (exclusive)
int randomInt = ThreadLocalRandom.current().nextInt(1, 101)
ThreadLocalRandom
是在 Java 中生成随机数的几种方法之一,包括较旧的 Math.random()
方法和 java.util.Random
类。 ThreadLocalRandom
的优点是它是专门设计用于单个线程中的,避免了其他实现带来的额外线程同步成本。因此,它通常是在安全敏感上下文之外使用的最佳内置随机实现。
如果适用,在并发程序中使用
而不是共享ThreadLocalRandom
对象通常会遇到更少的开销和争用。Random
这是一种干净且有效的方法,带有范围检查!享受吧。
public double randDouble(double bound1, double bound2) {
//make sure bound2> bound1
double min = Math.min(bound1, bound2);
double max = Math.max(bound1, bound2);
//math.random gives random number from 0 to 1
return min + (Math.random() * (max - min));
}
//稍后调用:
randDouble(1,100)
//example result:
//56.736451234
我会写 int 数字 = 1 + (int) (Math.random() * 100);
您可以使用以下代码:
int randomNumber = (int)Math.round(Math.random() * 100);
double random = Math.random();
double x = random*100;
int y = (int)x + 1; //Add 1 to change the range to 1 - 100 instead of 0 - 99
System.out.println("Random Number :");
System.out.println(y);