1 //生成四位的验证码 2 3 4 //利用split截取 5 6 String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 7 8 String []str1 = str.split("");//分割字符串,并生成数组 9 10 // for(String x:str1){ 11 // 12 // System.out.println(x); 13 // } 14 String Code = "";//声明一个空的字符串 15 16 Random ran = new Random(); 17 18 for(int i = 0;i<4;i++){ 19 20 int j = ran.nextInt(62); 21 22 if(j == 0){ //去除split分割出来的那个空的char 23 24 Code = Code + str1[j+1]; 25 } 26 else{ 27 28 Code = Code + str1[j]; 29 } 30 } 31 System.out.println("生成的验证码1是:"+Code); 32 33 34 //利用subSting来分割 35 36 str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 37 38 Random ran1 = new Random(); 39 40 System.out.print("生成的验证码2是:"); 41 42 for(int a = 0;a<4;a++){ //循环四次截取四个字符串 43 44 int i = ran1.nextInt(str.length()-1); 45 46 System.out.print(str.substring(i,i+1)); 47 } 48 System.out.println(); 49 50
运行的结果:
原文:http://www.cnblogs.com/zhengfengyun/p/5132242.html