Code:
import java.util.Random;
public class RandomLetterUtil {
public static String getRandomCode(int size) { // 传入要生成的随机数的位数
Random random = new Random();
String str = "";
for (int i = 0; i < size; i++) {
int key = random.nextInt(2);
switch (key) {
case 0:
char code1 = (char) (random.nextInt(26) + 65);
str += code1;
break;
case 1:
char code2 = (char) (random.nextInt(26) + 97);
str += code2;
break;
}
}
return str;
}
// 主函数测试
public static void main(String[] args) {
int size = 100;
String randomCode = getRandomCode(size); // 传入要生成的随机数的位数
System.out.println("随机生成的"+size+"位数为:"+randomCode);
}
}
Renderings:
4:
6:
8:
12:
20:
100:
We first determine the number of bits before returning to look for generating random numbers is not meet the requirements, return str in the method; before adding an output str. length ();
System.out.println("随机生成的位数为:"+str.length());