博客
关于我
Java随机生成n位验证码
阅读量:801 次
发布时间:2023-01-29

本文共 1056 字,大约阅读时间需要 3 分钟。

Java随机验证码生成实现

在今天的学习中,我实现了一个随机生成验证码的功能,验证码长度可以是4位或6位,包含字母、大小写和数字。以下是代码和运行结果的展示:


代码示例

package com.itheima.hello;
public class ScannerDemo1 {
public static void main(String[] args) {
System.out.println(getCode(4));
System.out.println(getCode(6));
}
public static String getCode(int n) {
StringBuilder code = new StringBuilder();
for (int i = 0; i < n; i++) {
// 随机选择字符类型
int type = (int) Math.floor(Math.random() * 3);
switch(type) {
case 0: // 字母(大写)
code.append(ABCDEFGHIJKLMNOPQRSTUVWXYZ.charAt(Math.random() * 26));
break;
case 1: // 字母(小写)
code.append(abcdefghijklmnopqrstuvwxyz.charAt(Math.random() * 26));
break;
case 2: // 数字
code.append(String.valueOf(Math.random() * 10).charAt(0));
break;
}
}
return code.toString();
}
}

运行结果

运行代码后,随机生成的4位验证码为:7Q33

随机生成的6位验证码为:0FIiwD

转载地址:http://ytryk.baihongyu.com/

你可能感兴趣的文章