java如何编写生成验证码

随机生成由数字,字母大小写组成的验证码

1、创建verificationCode方法,创建时注意返回值类型为String,参数列表int a接收验证码长度

2、用Random方法随机出0,1,2三个数字,0代表数字,1代表大写字母,2代表小写字母

3、用switch做值的匹配,在case 0中随机获得0~9数字、case 1 中随机获得大写字母在ascii码表中对应值,case 2 中随机获得小写字母在ascii码表中对应值,并强制转换为char类型

4、最后循环,并把每一次循环的结果拼接即可

package com.test;

import java.util.Random;

public class Demo02 {
    public static void main(String[] args) {
//        调用verificationCode方法,并给定验证码长度
        String verification_code = verificationCode(6);
        System.out.println("验证码为:" + verification_code);
    }
//定义verificationCode方法
    public static String verificationCode(int a) {
//        定义一个空字符串
        String verification_code = "";
//        创建Random对象
        Random r = new Random();
        for (int i = 0; i < a; i++) {
//            确定字符类型(0代表数字,1代表大写字母,2代表小写字母)
            int type = r.nextInt(3);
            switch (type) {
                case 0:
//                    随机生成一个0~9数字
                    verification_code += r.nextInt(10);
                    break;
                case 1:
//                    随机生成一个65~90的数字,然后强转为大写字母
                    verification_code += (char) (r.nextInt(26) + 65);
                    break;
                case 2:
//                    随机生成一个97~122的数字,然后强转为小写字母
                    verification_code += (char) (r.nextInt(26) + 97);
                    break;
            }
        }
        return verification_code;
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值