【问题标题】:java random number bound by a variable由变量绑定的java随机数
【发布时间】:2021-03-27 03:29:48
【问题描述】:

我有两个随机生成的整数变量

int scoreWon = random1.nextInt(20);
int scoreLost = random1.nextInt();

我想要做的是,将scoreLost 的值与scoreWon 绑定,这样生成的数字将始终小于scoreWon 生成的值。

这样可以吗?

int scoreWon = random1.nextInt(20);
int scoreLost = random1.nextInt(scoreWon);

或者请帮帮我

【问题讨论】:

标签: java random integer


【解决方案1】:

是的,这可能是最好的方法。 Random.nextInt(int bound) 方法返回一个从 0bound-1 的数字(绑定是 exclusive),如下所述:

Random.nextInt documentation

示例:Random.nextInt(100) 将是 0...99

在您的上下文中:

Random random = new Random();
int scoreWon = random.nextInt(20); //0...19
int scoreLost = random.nextInt(scoreWon); //0...18

【讨论】:

    【解决方案2】:

    是的,这是可能的。就试一试吧。 nextInt() 的 int 参数是新随机整数值的上限(不包括)(下限为 0,包括)。

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 2020-06-29
      • 2017-09-21
      • 2011-05-03
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多