生成随机数随机字符
<ul>
<li>生成指定位数的随机数</li>
</ul>
<pre><code> /**
* 随机生成几位数
* @param num 位数
* @return
*/
public static String code(int num) {
double rand = Math.random();
//乘以9 + 1 而不直接乘以10是因为 要保证 前半部分一定大于1(+1后一定大于1) 如果生成0.00023 乘以10会导致位数不够
String code = (int) ((rand * 9 + 1) * Math.pow(10, num - 1)) + "";
return code;
}</code></pre>
<ul>
<li>生成指定位数的随机字符串</li>
</ul>
<pre><code>/**
* 返回指定位数的随机字符
*
* @param num
* @return
*/
public static String charCode(int num) {
Random rand = new Random();
String string = "";
for (int i = 0; i < num; i++) {
//ASCII a-z 97 -122
int randNum = rand.nextInt(26) + 97;
//ASCII转字符
char codec = (char) randNum;
String codestr = codec + "";
string += codestr;
}
return string;
}</code></pre>
<ul>
<li>生成指定位数随机字符串</li>
</ul>
<pre><code> /**
* 基础要素数据池
*/
static List<String> list = new ArrayList<>();
/**
* 填充数字
*/
public static void addNum() {
for (int i = 0; i < 10; i++) {
list.add(i + "");
}
}
/**
* 填充字符
*/
public static void addChar() {
for (int i = 97; i < 123; i++) {
//数字转字符
list.add(numConvertChar(i) + "");
}
}
/**
* 返回指定位数的数字加字母字符串
*
* @param num
* @return
*/
public static String randCNum(int num) {
addChar();
addNum();
int max = list.size();
String string = "";
int index1 = 0;
for (int i = 0; i < num; i++) {
//第一次随机
Random random = new Random();
int index = random.nextInt(max);
//根据随机结果进行 次数循环
for (int f = 0; f < index; f++) {
index1 = (int) (Math.random() * (max + 1));
}
index = index1 - 1;
index = index >= 0 ? index : index + 1;
string += list.get(index);
}
return string;
}
</code></pre>