素材巴巴 > 程序开发 >

Java中生成指定长度验证码

程序开发 2023-09-15 21:57:02

Java中生成指定长度验证码

1.方法一:执行效率高

  /*** 生成指定位数验证码,纯数字运算效率最高** @param maxSize* @return*/public static Long generateRandomCode(int maxSize) {if (maxSize < 0) {throw new BizException(ErrorCodeEnum.PARAM_ERROR);}//小数点后16位的double乘以10的指定次幂然后取整String code = String.valueOf((int) ((Math.random() * 9 + 1) * Math.pow(10, maxSize - 1)));Long resultCode = Long.valueOf(code);return resultCode;}

image-20230703103143729

2.方法二:字符串截取

    /*** 生成指定位数验证码,字符串截取,效率不如方法一** @param maxSize* @return*/public static Long generateSubStringCode(int maxSize) {if (maxSize < 0) {throw new BizException(ErrorCodeEnum.PARAM_ERROR);}//16位double小数,取小数点后的2-8位int startNum = 2;int endNum = startNum + maxSize;String code = (Math.random() + "").substring(startNum, endNum);Long resultCode = Long.valueOf(code);return resultCode;}
 

image-20230703104059937


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。