5.随机数
程序员文章站
2022-07-14 20:11:55
...
一.Random
新建RandomDemo.java
public class RandomDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(5);
//生成五位随机数,但是UUID只能生成到f而且没有大写
sb.append(UUID.randomUUID().toString().substring(2, 7));
System.out.println(sb.toString());
//创建一个包含大小写英文字母,和数字的StringBuilder
StringBuilder strb = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
strb.append(strb.toString().toUpperCase());
strb.append("0123456789");
StringBuilder sb2 = new StringBuilder(5);
for (int j = 0; j < 5; j++) {
//通过生成随机索引,返回该索引的字符
int i = new Random().nextInt(strb.length() - 1);
sb2.append(strb.charAt(i));
}
System.out.println(sb2);
}
}
二.ThreadLocalRandom
ThreadLocalRandom tlr = ThreadLocalRandom.current();
System.out.println(tlr.nextInt(10));//生成0-10之间的随机数
System.out.println(tlr.nextInt(5,10));//生成5-10之间的随机数
三.UUID
StringBuilder sb = new StringBuilder(5);
//生成五位随机数,但是UUID只能生成到f而且没有大写
sb.append(UUID.randomUUID().toString().substring(2, 7));
System.out.println(sb.toString());