随机生成字母在前,数字在后的随机数,具体多少为可自行设置
import java.util.Random;
/**
* @author lqf
* @date 2021/4/29---16:03
* @describe 生成随机数
*/
public class TestRandom {
public String getRandom(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
//todo 生成随机数类型
int isChar = 0; //todo 字母
int isFigure = 0; //todo 数字
for (int i = 0; i <= length; i++) {
//todo 生成随机的字母+数字字符串
String charOrNum = random.nextInt(2) / 2 == 0 ? "char" : "figure";
if (isChar >= 2) {
charOrNum = "figure";
}
if (isFigure >= 6) {
charOrNum = "char";
}
//todo 输出字母还是数字 忽略大小写
if ("char".equalsIgnoreCase(charOrNum)) {
sb.append((char) (random.nextInt(26) + 65)); //todo 强转字符
isChar++;
} else if ("figure".equalsIgnoreCase(charOrNum)) {
sb.append(random.nextInt(10));
isChar++;
}
}
return sb.toString();
}
//todo 测试主方法
public static void main(String[] args) {
TestRandom tr = new TestRandom();
System.out.println("随机数==" + tr.getRandom(7));
}
}
结果: