生成大小字母以及数字混乱的6位验证码
需求:生成大小字母以及数字混乱的6位验证码
1 public class VerifyCode { 2 public static String getCode(int length){ 3 String code = ""; 4 for(int i=0;i<length;i++){ 5 boolean boo = (int)(Math.random()*2)==0; 6 if(boo){ 7 code += String.valueOf((int)(Math.random()*10)); 8 }else { 9 int temp = (int)(Math.random()*2)==0?65:97; 10 char ch = (char)(Math.random()*26+temp); 11 code += String.valueOf(ch); 12 } 13 } 14 return code; 15 } 16 17 public static void main(String[] args) { 18 19 System.out.println(VerifyCode.getCode(6)); 20 System.out.println("-----------------"); 21 System.out.println(VerifyCode.getVerify(6)); 22 } 23 24 public static String getVerify(int length){ 25 String code = ""; 26 String str = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASFGHJKLZXCVBNM"; 27 String[] strs = str.split(""); 28 for(int i = 0;i<length;i++){ 29 code += strs[(int)(Math.random()*strs.length)]; 30 } 31 return code; 32 } 33 }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * @author Administrator * 随机生成6位验证码 */ public class Test01 { public static void main(String[] args) { //创建一个ArrayList集合,存放生成的代码 List<Object> list = new ArrayList(); //for循环生成6位验证码 for(int i = 0;i<6;i++) { //if语句交替判断生成数字或者字母 if(i%2==0) { int b = (int)(Math.random()*10);//生成0~9的数字 list.add(b); }else { boolean flag = false; do { int a = (int)(Math.random()*58+65);//生成大小写字母的ASCII码 //if排斥多余的中间其他字符 if(!(a>=91&&a<=95)) { String s = (char)a+"";//数字转字母 list.add(s); flag = true; } }while(!flag); } } Collections.shuffle(list);//shuffle随机排序 String out = new String(); for(Object s : list) { out+=s; } System.out.println(out.toString()); } }