在Java中的范围内统一生成安全随机数
如何在一个范围内生成安全的统一随机数? 范围可以在0到100之间。(上限不是2的幂)。
java.security.SecureRandom
似乎提供范围0..2^n
。
你可以做
Random rand = new SecureRandom() // 0 to 100 inclusive. int number = rand.nextInt(101);
要么
// 0 inclusive to 100 exclusive. int number = rand.nextInt(100);
注意:这比say (int) (rand.nexDouble() * 100)
更有效,因为nextDouble()需要创建至少53位的随机性,而nextInt(100)创建少于7位。
尝试下面的代码快照
SecureRandom random = new SecureRandom(); int max=50; int min =1; System.out.println(random.nextInt(max-min+1)+min);
- 如何在struts2中禁止缓存?
- 列表实现:LinkedList与ArrayList和TreeList相比真的表现不佳吗?
- 参数传递为Struts 2中静态包含的页面
- 如何在Java 1.4中设置BufferedReader和PrintWriter的超时?
- Charset做的ByteBuffer.asCharBuffer()使用什么?
- 如何在LibGDX中绘制BitmapFont?
- 每条消息都需要Cipher.init()吗?
- java.lang.NoSuchMethodError:org.springframework.web.context.ConfigurableWebApplicationContext.setId(Ljava / lang / String;)V
- 防止在selenium webdriver测试中加载外部内容