栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

import java.util.concurrent.ThreadLocalRandom;// nextInt is normally exclusive of the top value,// so add 1 to make it inclusiveint randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

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

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

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

import java.util.Random;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完成任务时,就无需重新发明随机整数生成轮。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419489.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号