生成随机验证码

package com.itheima.demo;

import java.util.Random;

public class Test3 {
    public static void main(String[] args) {
        // 需求:生成一个由大写字母 小写字母 数字组成的一个五位数的随机验证码
        String code = creatcode(5);
        System.out.println("随机验证码是" + code);

    }
     //1.定义一个方法返回一个随机码,返回值类型String
    public static String creatcode(int n) {
        String code = "";
        Random r = new Random();
        //2.定义一个For循环 循环n次,一依次生成随机字符
        for (int i = 0; i < n; i++) {
            //i= 0 1 2 3 4
            //3.生成一个随机字符:大写字符 小写字符 数字字符
            int type = r.nextInt(3);//0 1 2
            switch (type) {
                case 0:
                    //大写字符(A 65 - Z 65+25 )
                    char ch = (char) (r.nextInt(26) + 65);
                    code += ch;
                    break;
                case 1:
                    //小写字符(a 97 - z 97+25)
                    char ch1 = (char) (r.nextInt(26) + 97);
                    code += ch1;
                    break;
                case 2:
                    //数字字符
                    code += r.nextInt(10);
                    break;
            }
        }
    return code;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值