java-随机数

来源:互联网 发布:mysql 开放远程访问 编辑:程序博客网 时间:2024/06/11 00:52

1、随机生成32位UUID

public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",            "W", "X", "Y", "Z" };public static String generateShortUuid() {    StringBuffer shortBuffer = new StringBuffer();    String uuid = UUID.randomUUID().toString().replace("-", "");    for (int i = 0; i < 8; i++) {        String str = uuid.substring(i * 4, i * 4 + 4);        int x = Integer.parseInt(str, 16);        shortBuffer.append(chars[x % 0x3E]);    }    return shortBuffer.toString();}

2、Random类的使用

Random random = new Random(10);

强调:10为种子数,种子数只是随机算法的起源数字,和生成的随机数字的区间无关。
常用方法:
1. nextBoolean()
2. nextDouble(),随机的double值,数值介于[0,1.0)之间
3. nextInt(),随机的int值,该值介于int的区间,也就是-231到231-1之间
4. nextInt(n),随机的int值,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n
5. 生成[0,5.0)区间的小数
double d2 = r.nextDouble() * 5;
6. 生成[1,2.5)区间的小数
double d3 = r.nextDouble() * 1.5 + 1;
7. 生成[-3,15)区间的整数
int n4 = r.nextInt(18) - 3;
8.

原创粉丝点击