英文标题【random】
有关本页中使用的代码,请访问 GitHub 中的链接:
random() 方法用于返回一个随机数,随机数范围为 0.0 =< Math.random < 1.0。
这是一个默认方法,不接受任何参数。
该方法返回 double 值。
实例
实例测试如下:
/** * Random from JDK */ @Test public void testRandom() { logger.debug("{}", Math.random()); logger.debug("{}", Math.random()); }
结果输出:
2018/12/30 16:40:51 DEBUG [com.ossez.codebank.lang.tests.NumberTest] - 0.6805814328498536 2018/12/30 16:40:51 DEBUG [com.ossez.codebank.lang.tests.NumberTest] - 0.3476033279725307
产生指定范围的随机数
在很多时候你可能需要上传指定范围的随机数。
比如说,如何产生 1 - 100 的随机数。
Math.random()
Math.random() 可以产生一个 大于等于 0 且 小于 1 的双精度伪随机数,假设需要产生 ”0<= 随机数 <=10” 的随机数,可以这样做:
int num =(int)(Math.random() * 11);
那如何产生 “5 <= 随机数 <= 10” 的随机数呢?
int num = 5 + (int)(Math.random() * 6);
生成 “min <= 随机数 <= max ” 的随机数
int num = min + (int)(Math.random() * (max-min+1));
请参考下面的代码:
/** * Random Interval from JDK */ @Test public void testRandomInterval() { logger.debug("0 <= R <= 10 - [{}]", (int) (Math.random() * 11)); logger.debug("5 <= R <= 10 - [{}] ", 5 + (int) (Math.random() * 6)); int min = 1; int max = 100; logger.debug("min <= R <= max - [{}] ", min + (int) (Math.random() * (max - min + 1))); }
程序输出:
2018/12/30 16:52:40 DEBUG [com.ossez.codebank.lang.tests.NumberTest] - 0 <= R <= 10 - [10] 2018/12/30 16:52:40 DEBUG [com.ossez.codebank.lang.tests.NumberTest] - 5 <= R <= 10 - [8] 2018/12/30 16:52:40 DEBUG [com.ossez.codebank.lang.tests.NumberTest] - min <= R <= max - [41]
Commons Lang
在实际使用中,没有必要区重新写一次这些随机数的生成规则,可以借助一些标准库完成。如 commons-lang.
org.apache.commons.lang3.RandomUtils 和 org.apache.commons.lang.RandomStringUtils 2 个工具类。
提供了如下产生指定范围的随机数方法和返回指定长度的随机字符串的方法。
指定的方法如下:
/** * Random Interval from JDK */ @Test public void testRandomCommonsLang() { int startInclusive = 1; int endExclusive = 100; logger.debug("min <= R <= max - [{}] ", RandomUtils.nextInt(startInclusive, endExclusive)); logger.debug("min <= R <= max - [{}] ", RandomUtils.nextFloat(startInclusive, endExclusive)); logger.debug("min <= R <= max - [{}] ", RandomUtils.nextDouble(startInclusive, endExclusive)); logger.debug("RandomStringUtils - [{}]", RandomStringUtils.randomAlphanumeric(10)); }
上面的程序输出为:
2018/12/30 17:01:57 DEBUG [com.ossez.codebank.lang.tests.NumberTest] - min <= R <= max - [42] 2018/12/30 17:01:57 DEBUG [com.ossez.codebank.lang.tests.NumberTest] - min <= R <= max - [47.070007] 2018/12/30 17:01:57 DEBUG [com.ossez.codebank.lang.tests.NumberTest] - min <= R <= max - [75.57927383362804] 2018/12/30 17:01:57 DEBUG [com.ossez.codebank.lang.tests.NumberTest] - 9ZhT1dDl49