好问题
Good  Question
  • 首 页
  • 问题
    • PHP
    • JAVA
    • CPlusPlus
    • C#
    • SQL
  • 关 于
  • 联 系
使用JAVA在一特定范围引入随机整数 关闭 返回上一级  

使用JAVA在一特定范围引入随机整数
+ 查看更多

发布日期:2018-03-10 14:26
分类:JAVA
浏览次数:117
我想在Java编程中引入一特定范围中的随机int型值。
例如:
我的范围为5-10,那么5就是最小可能值,10就是最大可能值,这范围中的其他数值都可能成为可能值。
在Java中,有一个Math类中的方法random(),返回一个double类型范围0.0-1.0的值。在类Random()中有一个nextInt(int n)方法,返回一个范围为0(包括)到n(不包括)int类型随机值,我找不到一个能返回两数之间一随机整型数的方法。
我尝试过用下面的解决办法但是还是有问题:(极小值和极大值是最小的和最大的数)。
办法1:
randomNum = minimum + (int)(Math.random() * maximum);
问题:
randomNum可能比最大值还要大。
办法2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
问题:
randomNum可能比最小值还要小。
我能怎么解决该问题?
我搜索过一些档案发现:
Expand a random range from 1–5 to 1–7
Generate random numbers uniformly over an entire range
但是我还是没有解决问题。
h2. 回答
在Java1.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);
the relevant JavaDoc中讲到这个方法的优点在于不用显式初始化一个java.util.Random用例,但是这可能因不恰当使用导致混乱和错误。
反而言之,因为没有办法显式化出初始用例,在测试或者保存游戏状态类似情况时就很难去复制结果,在这种情况下,Java1.7之前的技能就可以被使用了。
在Java1.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
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @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).
    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;
}
看the relevant JavaDoc.,实际上,类java.util.Random常常比java.lang.Math.random().更好使用
而且,在标准库中有直接的API可以完成任务就没必要重写这个随机整数方法。
上一篇如何在Java中故意制造一个内存泄漏
遍历HashMap下一篇
下一篇遍历HashMap

最新文章

  • 函数`__construct`用来干嘛的
    发布日期:2018-03-26
  • 通过访客的IP得到他们的地区
    发布日期:2018-03-26
  • 合并两个PHP对象的最好的方法是什么?
    发布日期:2018-03-26
  • 该如何把一该如何把一个对象转化成数组?
    发布日期:2018-03-26
  • 什么是输出缓冲区?
    发布日期:2018-03-26
  • 在PHP中怎么把用逗号分隔的字符串分隔在一个数组里?
    发布日期:2018-03-26
  • 在PHP中使用foreach循环时查找数组的最后一个元素
    发布日期:2018-03-26
关于好问
收集整理一些有用的问题和回答,造福中国的程序旺和IT喵们!
友情链接
起飞页 
相关信息
版权声明
Copyright © 2016 - 2022  苏州卡达网络科技有限公司 备案号:苏ICP备09008221号