为Random.nextInt()指定最大值和最小值? [英] Specify max and min for Random.nextInt()?

查看:74
本文介绍了为Random.nextInt()指定最大值和最小值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Java:生成一定范围内的随机数

Possible Duplicate:
Java: generating random number in a range

我想在逻辑范围内生成一个随机整数.因此,举例来说,我正在编写一个程序来掷掷"具有指定边数的骰子.

I want to generate a random int in a logical range. So, say for example, I'm writing a program to "roll" a dice with a specified number of sides.

public int rollDice() {
     Random generator = new Random();
     return generator.nextInt(sides);
}

现在的问题是这将返回边和零之间的值,包含,这没有任何意义,因为大多数骰子从1到6、9等.所以我如何指定nextInt应该工作在1到边数之间?

Now the problem becomes that this will return values between sides and zero, inclusive, which makes no sense because most dice go from 1 to 6, 9, etc. So how can I specify that nextInt should work between 1 and the number of sides?

推荐答案

要在 from to (含)之间生成随机的int值(均匀分布),请使用:

To generate a random int value (uniform distribution) between from and to (inclusive) use:

from + rndGenerator.nextInt(to - from + 1)

以您的情况(1 ..面):

In your case (1..sides):

1 + rndGenerator.nextInt(sides)

这篇关于为Random.nextInt()指定最大值和最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆