public class yanzhengma { public static void main(String[] args) { //随机验证码 String code=createCode(4); System.out.println(code); } //1、定义一个方法返回值随机验证码:是否需要返回值类申明?String 是否申明形参:int n public static String createCode(int n){ //4、定义一个字符串变量生成随机字符 String code=""; Random r=new Random(); //2、定义for循环,循环n次,形成随机字符 for (int i = 0; i < n; i++) { //3、生成一个随机字符:英文大写 小写 数字(0 1 2) int type = r.nextInt(3);//0 1 2 switch(type){ case 0: //定义成大写字符(A-Z 65+25)(0-25) + 65 char ch=(char)(r.nextInt(26)+ 65); code +=ch; break; case 1: //定义成小写字符(a-z 97+25)(0-25) + 97 char ch1=(char)(r.nextInt(26)+ 97); code +=ch1; break; case 2: //定义成数字 0-9 code +=r.nextInt(10); break; } } return code; } }
Java脚本写的随机验证码
最新推荐文章于 2024-07-24 17:27:32 发布