本文共 1056 字,大约阅读时间需要 3 分钟。
在今天的学习中,我实现了一个随机生成验证码的功能,验证码长度可以是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/