博客
关于我
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/

你可能感兴趣的文章
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:128
查看>>
nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in usrlocalnginxconfnginx.conf128
查看>>
nginx日志分割并定期删除
查看>>
Nginx日志分析系统---ElasticStack(ELK)工作笔记001
查看>>
Nginx映射本地json文件,配置解决浏览器跨域问题,提供前端get请求模拟数据
查看>>
nginx最最最详细教程来了
查看>>
Nginx服务器---正向代理
查看>>
Nginx服务器上安装SSL证书
查看>>
Nginx服务器基本配置
查看>>
Nginx服务器的安装
查看>>
Nginx标准配置文件(包括反向代理、大文件上传、Https证书配置、文件预览等)
查看>>
Nginx模块 ngx_http_limit_conn_module 限制连接数
查看>>
Nginx模块 ngx_http_limit_req_module 限制请求速率
查看>>
nginx添加模块与https支持
查看>>
nginx状态监控
查看>>
Nginx用户认证
查看>>
Nginx的location匹配规则的关键问题详解
查看>>
Nginx的Rewrite正则表达式,匹配非某单词
查看>>
Nginx的使用总结(一)
查看>>
Nginx的使用总结(三)
查看>>