1、在日常开发中经常用到随机数,或在多线程测试的等待中经常用随机毫秒数;
2、先举例java中常用的两种最基本的生成随机数的方法;
3、读者可以根据实际情况,在两种基本方法上衍生或扩展,比如生辰6位固定随机数(短信验证码)等。
1、两种最基本的随机数生成方式举例:
package com.liuxd.random;
import java.util.Random;
/**
* Created by Liuxd on 2018/9/5.
*/
public class TestRandom {
public static void main(String[] args) {
Random random = new Random();
int num1 = random.nextInt(1000);
System.out.println("使用Random类,生成随机数:" + num1);
System.out.println("------------------------");
int num2 = (int) (Math.random() * 1000);
System.out.println("使用Math类,生成随机数:" + num2);
}
}
2、6位短信验证码举例
package com.liuxd.random;
/**
* Created by Liuxd on 2018/9/5.
*/
public class TestRandom {
public static String getCode1() {
Integer intFlag = (int) (Math.random() * 1000000);
String flag = intFlag.toString();
if (flag.length() == 6 && flag.startsWith("9")) {
return intFlag.toString();
} else {
intFlag = intFlag + 100000;
return intFlag.toString();
}
}
public static String getCode2() {
return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(getCode1());
}
System.out.println("---------------------------------");
for (int i = 0; i < 10; i++) {
System.out.println(getCode2());
}
}
}