java如何隨機生成定長的字符串
阿新 • • 發佈:2018-09-26
時間 tle eof 長度 bcd pow val gnu 字符串
小數,字符串、時間等示例代碼
public class RandomTest {
public static Random rand = new Random();
public static String dateStart = "2017-01-01 00:00:00";
/**
* hh 表示12小時制
* HH 表示24小時制
*/
public static SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
public static SimpleDateFormat format1 = new SimpleDateFormat("YYYYMMDDHHmmss");
public static void main(String[] args) throws ParseException {
System.out.println(getDouble());
long timeStart = 1483200000000l;
System.out.println(format.parse(dateStart).getTime());
System.out.println(format.format(new Date(timeStart)));
System.out.println(format.format(new Date(timeStart+1000)));
System.out.println(format.format(new Date(timeStart+2000)));
format.format(new Date());
System.out.println(getRandomString(2));
}
/**
* 隨機生成指定精確度的小數
* @return
*/
public static double getDouble(){
DecimalFormat df=new DecimalFormat("#.000000");
int a=(int)(Math.random()*2+1);
int aa=(int)(Math.pow(-1, a));
return Double.valueOf(df.format(rand.nextDouble()*100*aa));
}
/**
* 生成固長字符串
* @param length
* @return
*/
public static String getRandomString(int length) { //length表示生成字符串的長度
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 生成固長字符串
* @param length
* @return
*/
public static String getRandomStringNum(int length) { //length表示生成字符串的長度
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
--------------------- 本文來自 AngelaPotato 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/wangxilong1991/article/details/72636482?utm_source=copy
java如何隨機生成定長的字符串