java设计一个程序产生6位的大小写字母和数字的验证码 例如: 随机验证码:E2DC3u 随机验证码:sMZA1F
时间: 2024-11-12 13:37:04 浏览: 18
在Java中,你可以使用`java.util.Random`类和`StringBuilder`来生成一个六位的大小写字母和数字的随机验证码。以下是一个简单的示例代码:
```java
import java.util.Random;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CaptchaGenerator {
private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase();
private static final String NUMBERS = "0123456789";
public static void main(String[] args) {
generateAndPrintCaptcha(6);
}
public static String generateCaptcha(int length) {
Random random = new Random();
StringBuilder captcha = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int type = random.nextInt(3); // 0 for lower case, 1 for upper case, 2 for number
switch (type) {
case 0:
captcha.append(CHAR_LOWER.charAt(random.nextInt(CHAR_LOWER.length())));
break;
case 1:
captcha.append(CHAR_UPPER.charAt(random.nextInt(CHAR_UPPER.length())));
break;
case 2:
captcha.append(NUMBERS.charAt(random.nextInt(NUMBERS.length())));
break;
}
}
return captcha.toString();
}
public static void generateAndPrintCaptcha(int length) {
String captcha = generateCaptcha(length);
System.out.println("随机验证码: " + captcha);
}
}
```
这个程序会生成一个长度为6的字符串,包含大写字母、小写字母和数字。每次运行都会得到一个不同的验证码。
阅读全文