1. 首页
  2. 软件开发
  3. JAVA
  4. JAVA生成验证码

JAVA生成验证码

  • 发布于 2024-09-21
  • 0 次阅读

从字符数组中随机选取字符并产生新的字符串。

代码主体:

  //验证码的生成
    public static void main(String[] args) {
        //定义一个字符库
        //字符库中的所有字符都以单字符的形态存在
        char[] code = {'A', 'B', 'C', '1', '2', '3', '#', '@'};
        System.out.println("这是库:'A', 'B', 'C', '1', '2', '3', '#', '@'");
        //电脑随机数命令
        Random random = new Random();
        //定义新的空字符串
        String res = "";
        //用for循环将选中的单字符赋给字符串
        for (int i = 0; i < 4; i++) {
            //电脑随机生成数字
            //生成数字的范围是字符库中字符的角标
            //将角标赋给变量i1
            int i1 = random.nextInt(code.length);
            //将i1拿到的角标对应的字符挨个拼接到刚定义的新字符串中
            //这样就获得了一个符合要求的字符串
            res += code[i1];
        }
       //输出该字符串
        System.out.println("res = " + res);
    }
}

输出结果:

这是库:'A', 'B', 'C', '1', '2', '3', '#', '@'
res = 3@AC

Process finished with exit code 0
```java
这是库:'A', 'B', 'C', '1', '2', '3', '#', '@'
res = 3A2A

Process finished with exit code 0


原文链接: https://blog.csdn.net/daibadetianshi/article/details/136787900