Java 生成6位随机验证码 (包含数字和大写字母)
可以使用以下 Java 代码生成包含数字和大写字母的 6 位随机验证码:
import java.util.Random;
public class RandomCodeGenerator {
public static void main(String[] args) {
String code = generateCode();
System.out.println('验证码:' + code);
}
public static String generateCode() {
String code = '';
Random random = new Random();
for (int i = 0; i < 6; i++) {
int type = random.nextInt(2); // 0表示数字,1表示大写字母
if (type == 0) {
code += random.nextInt(10); // 生成0~9的随机数
} else {
code += (char) (random.nextInt(26) + 'A'); // 生成A~Z的随机大写字母
}
}
return code;
}
}
代码解析:
-
generateCode方法用于生成随机验证码,返回一个String类型的字符串。 -
在方法中定义一个空字符串
code,用于存储生成的验证码。 -
创建一个
Random对象,用于生成随机数。 -
使用
for循环生成 6 位验证码,每次循环生成一个数字或大写字母。 -
使用
random.nextInt(2)生成一个 0 或 1 的随机数,表示生成数字或大写字母。 -
如果随机数为 0,生成一个 0~9 的随机数,使用
random.nextInt(10)方法。 -
如果随机数为 1,生成一个 A~Z 的随机大写字母,使用
(char) (random.nextInt(26) + 'A')方法,其中'A'表示字符 A 的 ASCII 码,加上一个 0~25 的随机数,得到 A~Z 之间的随机大写字母。 -
将生成的数字或字母添加到
code字符串中。 -
循环结束后,返回生成的验证码字符串。
原文地址: https://www.cveoy.top/t/topic/j7Xl 著作权归作者所有。请勿转载和采集!