随机产生验证码是很常见也很简单的小算法,两层循环就可以搞定,随手记一下自己知道的两种比较常用的方法,以防忘记。
第一种:
首先定义一个char类型的包含字母和数字的数组
char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', '3', '4', '5', '6', '7', '8', '9' };
boolean[] flag = new boolean[chars.length];
char[] result = new char[5];
for (int i = 0; i < result.length; i++) { int j; do { j = new Random().nextInt(chars.length); } while (flag[j]); result[i] = chars[j]; flag[j] = true; }
String string = ""; for (int i = 0; i < result.length; i++) { string += result[i]; }
首先定义一个char类型
char[] a ={'A','B','C','D','E', 'F','G','H','I','J','K', 'L','M','N','O','P','Q', 'R','S','T','U','V','W', 'X','Z'};
char[] result =new char[5]; for(int i=0;i<5;i++){ int j= i+ new Random().nextInt(a.length-i); result[i]= a[j]; char temp = a[i]; a[i]=a[j]; a[j]=temp; }
String s =""; for(int i=0;i<result.length;i++){ s += result[i]; }