Random获取随机数
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package com.example.demo; import java.util.Random; public class RandomDemo { public static void main(String[] args) { Random random = new Random(); // 指定边界 [0, bound) System.out.println(random.nextInt(10)); // 8 // [0, 1) System.out.println(Math.random()); // 0.4743026139690609 } }
更多随机数据获取方法
用到的依赖
复制代码
1
2
3
4
5
6<dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>
示例
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59package com.demo.random; import org.apache.commons.lang.RandomStringUtils; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class RandomDemo { public static void main(String[] args) throws NoSuchAlgorithmException { // 1、Random Random random = new Random(); System.out.println(random.nextDouble()); // 2、Math.random System.out.println(Math.random()); // 3、ThreadLocalRandom System.out.println(ThreadLocalRandom.current().nextDouble()); // 4、SecureRandom SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); System.out.println(secureRandom.nextDouble()); // 5、RandomStringUtils String result = RandomStringUtils.random(64); System.out.println(result); // 长度为64位的字符串 result = RandomStringUtils.randomAlphabetic(64); System.out.println(result); // 32位ascii码 result = RandomStringUtils.randomAscii(32); System.out.println(result); // 指定字符数组 result = RandomStringUtils.random(32, "qw32rfHIJk9iQ8Ud7h0X"); System.out.println(result); /** * 0.6842526472648046 * 0.968969349495142 * 0.27962124767826213 * 0.012367070163319283 * 汕真庣뉔햯殫腍ꡊꁝ㨂Ǒ蒐霫瓯䟤ሠ漧ᎊ????끘෦????惘횕緛????⫺ꟻ䟻↕㽱륪鶋㛿ᔑ㓇䢙뿍鼗ꦡ첡缹濎릅솣떽裴ﱆ뙠曜蘝せⶏ潻➣▨澜채 * niSaTPTkUfrdqjcgFbZcyAqdGsnZQKoKSWpUxYSffMDiNBMVBcGfkxGOphVkAhMe * :xB__?hx/W,,?7bEdr@~E4GjLh6yxp0U * I80QH8Uffwkh8r03ddrrHHUk8w9h0rJw */ } }
参考
Java 生成随机数的 5 种方式,你知道几种?
最后
以上就是激昂月光最近收集整理的关于Java:通过Random获取伪随机数的全部内容,更多相关Java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复