java 随机生成范围_如何在Java中生成特定范围内的随机整数?

小编典典

在Java 1.7或更高版本中,执行此操作的标准方法如下:

import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,

// so add 1 to make it inclusive

int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

请参阅相关的JavaDoc。这种方法的优点是不需要显式初始化java.util.Random实例,如果使用不当,可能会引起混乱和错误。

但是,相反,没有办法显式设置种子,因此在测试或保存游戏状态或类似情况有用的情况下,很难重现结果。在这种情况下,可以使用下面显示的Java 1.7之前的技术。

在Java 1.7之前,执行此操作的标准方法如下:

import java.util.Random;

/**

* Returns a pseudo-random number between min and max, inclusive.

* The difference between min and max can be at most

* Integer.MAX_VALUE - 1.

*

* @param min Minimum value

* @param max Maximum value. Must be greater than min.

* @return Integer between min and max, inclusive.

* @see java.util.Random#nextInt(int)

*/

public static int randInt(int min, int max) {

// NOTE: This will (intentionally) not run as written so that folks

// copy-pasting have to think about how to initialize their

// Random instance. Initialization of the Random instance is outside

// the main scope of the question, but some decent options are to have

// a field that is initialized once and then re-used as needed or to

// use ThreadLocalRandom (if using at least Java 1.7).

//

// In particular, do NOT do 'Random rand = new Random()' here or you

// will get not very good / not very random results.

Random rand;

// nextInt is normally exclusive of the top value,

// so add 1 to make it inclusive

int randomNum = rand.nextInt((max - min) + 1) + min;

return randomNum;

}

请参阅相关的JavaDoc。实际上,java.util.Random类通常比java.lang.Math.random()更可取。

特别是,当标准库中有简单的API完成任务时,就无需重新发明随机整数生成轮。

2020-11-23

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值