需求
需求:开发一个Java程序,可以生成指定位数的验证码,每位可以是数字、大小写字母。
方式
方式一
import java.util.Random;
public class VerificationCode2 {
public static void main(String[] args) {
// 需求:开发一个程序,可以生产指定位数的验证码,每位可以是数字、大小写字母
System.out.println(verificationcode(5));
}
public static String verificationcode(int a){
// 1、定义一个for循环用于控制产生多少位随机字符
Random r = new Random();
// 2、定义一个String类型的变量用于记住产生的每位随机字符
String code = "";
for (int i = 1; i <= a ; i++) {
// 为每个位置生产一个随机字符:可能是数字、大小写字母。
// 思路:随机一个 0 1 2之间的数字出来:0 代表随机一个数字,1 代表随机一个大写字母,2 代表随机一个小写字母
int type = r.nextInt(3);
switch (type){
case 0:
// 随机一个数字
code += r.nextInt(10); //0-9
break;
case 1:
// 随机一个大写字母
// A 65 Z 65+25 (0,25) +65
char AA = (char)(r.nextInt(26)+65);
code +=AA;
break;
case 2:
// 随机一个小写字母
// a 97 z 97+25 (0,25)+97
char aa = (char)(r.nextInt(26)+97);
code += aa;
break;
}
}
return code;
}
}
方式二
import java.util.Random;
public class VerificationCode1 {
public static void main(String[] args) {
// 需求:开发一个程序,可以生产指定位数的验证码,每位可以是数字、大小写字母
verificationcode(8);
}
public static void verificationcode(int a){
Random r = new Random();
String[] arr = {"1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
"Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r",
"s","t","u","v","w","x","y","z"};
String[] arr1 = new String[a];
for (int i = 0; i < a; i++) {
int b = r.nextInt(arr.length); // 0-61
arr1[i] = arr[b];
System.out.print(arr1[i] + " ");
}
}
}