一、Random类的nextInt()方法
用Random类的nextInt()方法生成随机数,import java.util.Random;
1、不带参数的nextInt()会生成所有有效的整数(包含正数,负数,0);
2、带参的nextInt(int x)则会生成一个范围在0~x(不包含x)的任意正整数。
二、Math.random()方法
random() 方法用于返回一个double类型的随机数,随机数范围为 [0.0, 1.0),左闭右开。
三、生成一个任意长度的随机字符串,随机字符有可能是数字,大写字母或者小写字母
应用场景:生成验证码。
public static String getRandomStr(int x) {
String str = "";
for(int i=0; i<x; i++) {
char c = '#';
while(!Character.isDigit(c) && !Character.isLetter(c)) {
c = (char) (new Random().nextInt(75) + 48); //数字和字母的ASCII码在48到122之间
}
str += c;
}
return str;
}
四、生成某一时间范围内的随机时间
思路:
1. 把起始时间和结束时间作为特定格式的字符串,再转换成时间
2. 用getTime()方法得到对应的long型的整数
3. 用Math.random()方法获取两个整数间的随机数。注意该方法的随机数范围是左闭右开,所以严格来说,两数做差需要再加1
4. 通过new Date(date)方法得到此随机数对应的时间
public static Date getRandomDate(String beginDate, String endDate) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date start = format.parse(beginDate);
Date end = format.parse(endDate);
if(start.getTime() >= end.getTime()){
return null;
}
//Math.random()随机数范围是左闭右开,所以严格来说,两数做差需要再加1
long date = (long) (Math.random()*(end.getTime()-start.getTime()+1)+start.getTime());
return new Date(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}