题目:开发一个程序,可以生成指定位数的验证码,可以是数字,也可以是大小写。
代码:下面是我写的,简单粗暴。
package com.lzk.test;
import java.util.MissingFormatArgumentException;
import java.util.Random;
public class test1 {
public static void main(String[] args) {
System.out.println(CreateCode(6));//输出6位随机验证码
}
public static String CreateCode (int n) {
Random r = new Random();
String code = "";//验证码字符串
for (int i = 0; i < n; i++) {
int type = r.nextInt(3); //随机生成0-2的随机数,来控制生成数字还是大小写
switch (type){
case 0:
code += (r.nextInt(10) );//生成0-9的随机数
break;
case 1:
code += (char) (r.nextInt(26) + 'a');//生成a-z的随机字母,'a'的ASCII码为97.所以可以改成97
break;
case 2:
code += (char) (r.nextInt(26) + 'A');//生成A-Z的随机字母,'A'的ASCII码为65.所以可以改成65
break;
}
}
return code;
}
}
GPT生成的代码,高级,
package com.lzk.test;
import java.util.Random;
public class VerificationCodeGenerator {
// 定义验证码的字符范围
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public static void main(String[] args) {
int length = 6; // 指定位数的验证码
String verificationCode = generateVerificationCode(length);
System.out.println("Generated Verification Code: " + verificationCode);
}
// 生成验证码的方法
public static String generateVerificationCode(int length) {
Random random = new Random();
StringBuilder verificationCode = new StringBuilder(length);// 创建一个StringBuilder对象来存储验证码
for (int i = 0; i < length; i++) {
int index = random.nextInt(CHARACTERS.length());// 随机获取一个字符的索引
verificationCode.append(CHARACTERS.charAt(index));// 根据索引获取字符并添加到验证码中
}
return verificationCode.toString();// 返回验证码字符串
}
}