Skip to content

Instantly share code, notes, and snippets.

@hhhaiai
Created July 30, 2020 07:54
Show Gist options
  • Save hhhaiai/1ea9e4d418d20e0b37b170e5500532df to your computer and use it in GitHub Desktop.
Save hhhaiai/1ea9e4d418d20e0b37b170e5500532df to your computer and use it in GitHub Desktop.
// 根据指定长度生成字母和数字的随机数
// 0~9的ASCII为48~57
// A~Z的ASCII为65~90
// a~z的ASCII为97~122
// https://blog.csdn.net/wangyy130/article/details/80084376
public static String createRandomCharData(int length) {
StringBuilder sb = new StringBuilder();
Random rand = new Random();// 随机用以下三个随机生成器
Random randdata = new Random();
int data = 0;
for (int i = 0; i < length; i++) {
rand = new Random(System.nanoTime());
randdata = new Random(System.nanoTime());
int index = rand.nextInt(3);
// 目的是随机选择生成数字,大小写字母
switch (index) {
case 0:
data = randdata.nextInt(10);// 仅仅会生成0~9
sb.append(data);
break;
case 1:
data = randdata.nextInt(26) + 65;// 保证只会产生65~90之间的整数
sb.append((char) data);
break;
case 2:
data = randdata.nextInt(26) + 97;// 保证只会产生97~122之间的整数
sb.append((char) data);
break;
}
}
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment