import java.util.Random; public class Test4 { public static void main(String[] args) { /* 生成验证码 内容:可以是小写字母,也可以是大写字母,还可以是数字 规则: 长度为5 内容中是四位字母,1位数字。 其中数字只有1位,但是可以出现在任意的位置。*/ //1.可以把所有的大写字母,小写字母都放到一个数组当中 char[] chs = new char[52]; //a-z A-Z for (int i = 0; i < chs.length; i++) { //利用ASCII码表 if (i <= 25){ //添加小写字母 chs[i] = (char)(97 + i); }else { // i > 25 //添加大写字母 //在ASCII码表中A---65 chs[i] = (char)(65 + i - 26); } } //2.从数组中随机获取4次 Random r = new Random(); String result = ""; for (int i = 0; i < 4; i++) { int arrIndex = r.nextInt(chs.length); result = result + chs[arrIndex]; } //3.生成一个0~9之间的随机数拼接到最后 //ACFG7 //思考,我们把7放到前面,修改了字符串的内容 //把生成的验证码先变成一个字符数组 //再让最后一个元素跟前面的随机位置的元素进行交换 //交换完毕之后再变成字符串就可以了。 int num = r.nextInt(10); result = result + num; String str = idCode(result); System.out.println(str); } //定义方法将数字放置在随机位置中 public static String idCode(String str){ Random r = new Random(); char[] arr = str.toCharArray(); int numIndex = r.nextInt(arr.length); char temp ; for (int i = 0; i < arr.length; i++) { temp = arr[numIndex]; arr[numIndex] = arr[arr.length - 1]; arr[arr.length - 1] = temp; } String result = new String(arr); return result; } }
数字可以在随机位置出现
运行结果:
思路来自:黑马程序员JAVA--阿伟