生成隨機數和字母(任意長度)
阿新 • • 發佈:2018-12-17
Java隨機數生成器:Random,ThreadLocalRandom,SecureRandom
@Test
public void getItemID(int n) {//n需要的長度
String val = "";
Random random = new Random();
for (int i = 0; i < n; i++) {
String str = random.nextInt(2) % 2 == 0 ? "num" : "char";
if ("char".equalsIgnoreCase(str)) { // 產生字母
int nextInt = random.nextInt(2) % 2 == 0 ? 65 : 97;
// System.out.println(nextInt + "!!!!"); 1,0,1,1,1,0,0
val += (char) (97 + random.nextInt(26));
} else if ("num".equalsIgnoreCase(str)) { // 產生數字
val += String.valueOf(random.nextInt(10));
}
}
System.out.println(val);
}
https://blog.csdn.net/qinchao_mei/article/details/80320896