用Java(8) 随机生成一一个指定长度及参数要求的验证码。参数有:是否包含数字、是否包含小写字母、是否包含大写字母、是否允许验证码有重复字符出现。 *随机生成--个指定长度及参数要求的验证码* @param len验证码长度 * @param isDigit 是否包含数字 * @param isl owerCase是否包含小写字母* @param isUpperCase是否包含大写字母* @param isRepeat是否允许验证码有重复字符出现 * @return验证码 public static String getCode(int len,booleanisDigit,boolean isL owerCase,boolean isUpperCase,boolean isRepeat)
时间: 2024-02-23 19:58:08 浏览: 92
好的,以下是用Java(8)随机生成指定长度及参数要求的验证码的代码:
```
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class VerificationCodeGenerator {
private static final String DIGITS = "0123456789";
private static final String LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
private static final String UPPER_CASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String getCode(int len, boolean isDigit, boolean isLowerCase, boolean isUpperCase, boolean isRepeat) {
if (!isDigit && !isLowerCase && !isUpperCase) {
throw new IllegalArgumentException("At least one of isDigit, isLowerCase and isUpperCase must be true");
}
if (len <= 0) {
throw new IllegalArgumentException("len must be greater than 0");
}
Random random = new Random();
List<Character> chars = new ArrayList<>();
if (isDigit) {
for (int i = 0; i < DIGITS.length(); i++) {
chars.add(DIGITS.charAt(i));
}
}
if (isLowerCase) {
for (int i = 0; i < LOWER_CASE_LETTERS.length(); i++) {
chars.add(LOWER_CASE_LETTERS.charAt(i));
}
}
if (isUpperCase) {
for (int i = 0; i < UPPER_CASE_LETTERS.length(); i++) {
chars.add(UPPER_CASE_LETTERS.charAt(i));
}
}
if (!isRepeat && chars.size() < len) {
throw new IllegalArgumentException("Not enough characters to generate a unique code");
}
StringBuilder codeBuilder = new StringBuilder(len);
for (int i = 0; i < len; i++) {
int index = random.nextInt(chars.size());
codeBuilder.append(chars.get(index));
if (!isRepeat) {
chars.remove(index);
}
}
return codeBuilder.toString();
}
}
```
调用方式示例:
```
String code = VerificationCodeGenerator.getCode(6, true, true, true, false);
System.out.println(code);
```
该示例调用方法生成一个长度为6的验证码,它包含数字、小写字母和大写字母,但不允许有重复字符出现。
阅读全文