我是靠谱客的博主 光亮火车,这篇文章主要介绍java中的 SecureRandom 简单用法(生成随机数),现在分享给大家,希望可以做个参考。

1.生成5位0~9的随机数

复制代码
1
2
3
4
5
6
7
8
9
10
SecureRandom random = new SecureRandom(); String returnValue = ""; int randomInt = 0; int range = 9; for(int i=0; i<5; i++ ){ randomInt = random.nextInt(range+1); returnValue = returnValue + randomInt; } System.out.println(returnValue);

做一个简单说明:

(1) range  :是代表随机生成数的最大值。

(2) random.nextInt(range+1)  :获取指定范围的随机数。比如:在上面的代码中range=9,说明生成的随机数在0~8中产生,因为nextInt(a)中a的取值是[0,a) ,是从0开始的,所以上面代码中才要把range+1。

 

举个例子就能很好理解:

复制代码
1
2
3
4
5
6
7
8
9
10
SecureRandom random = new SecureRandom(); String returnValue = ""; int randomInt = 0; int range = 1; for(int i=0; i<5; i++ ){ randomInt = random.nextInt(range); returnValue = returnValue + randomInt; } System.out.println(returnValue);

设定range=1,然后nextInt()中的range也不加上1 。可以看出只会出0这个数字。

 

(3) for循环的i值 :上面代码设定的是5,所以只会生成5位随机数。根据需求更改即可。

 

2.生成1位10000之内的随机数

复制代码
1
2
3
4
5
6
7
8
SecureRandom random = new SecureRandom(); String returnValue = ""; int randomInt = 0; int range = 10000; randomInt = random.nextInt(range); returnValue = returnValue + randomInt; System.out.println(returnValue);

这个没啥好讲解的,去掉for循环,增大随机数范围即可。

 

 

最后

以上就是光亮火车最近收集整理的关于java中的 SecureRandom 简单用法(生成随机数)的全部内容,更多相关java中的内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部