Random获取随机数
package 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 } }
更多随机数据获取方法
用到的依赖
<dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency>
示例
package 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 */ } }