public class 生成随机验证码 { public static void main(String[] args) { String abc = createCode(6);//n指验证码的数位; System.out.println(abc);//输出随机生成的验证码; } public static String createCode(int n){ Random r=new Random();//random方法生成随机数r; String shu = " ";//先定义一个字符串 shu 为空的,后续将随机生成的字符存储在shu字符串当中; for (int i = 1; i <=n ; i++) {//此处进行n次循环,每次生成一个随机数字; int type=r.nextInt(3);//此处随机生成0,1,2三个数字,0为生成数字0-9;1为生成A-Z,2为生成a-z; switch (type){ case 0: shu+=r.nextInt(10);//bound:10,生成0-9当中的数字;同理要生成0-n中的数字时,应当写bound:n+1; break; case 1: shu+=(char)(r.nextInt(26)+65);//此处生成大写字母,A的ASCII为65,共26个字母,可理解为固定值65加上0-25当中随机一个数组; //当此处bound生成的数字是0时,0+65=65,对应字符为A,同理bound生成的数字是3时,3+65=68,对应ascii字符为D; break; case 2: shu+=(char)(r.nextInt(26)+97);//此处为生成小写字母,原理同上;