验证码生成代码
package com.inspur;
import java.util.Scanner;
/**
* @author l
* @time 2020.11.12 9:17
* @ 产生一个区分大小写的四位数字字母组合验证码
*/
public class Captcha {
/**
* @return 产生一个0~9的数字
*/
private int math() {
return (int) (Math.random() * (9 - 0 + 1));
}
//产生一个0~9的数字
private int math2() {
return (int) (Math.random() * 10);
}
//产生一个a~z的字母(97-122)
private char math3() {
//其实此处直接换成26也可以
return (char) (Math.random() * (122 - 97 + 1) + 97);
}
//产生一个A~Z的字母(65-90)
private char math4() {
//其实此处直接换成26也可以
return (char) (Math.random() * (90 - 65 + 1) + 65);
}
public static boolean createCode() {
Captcha c = new Captcha();
//保存随机产生一个1-4的数字
int temp;
//初始化验证码
String code = "";
for (int i = 0; i < 4; i++) {
//随机选择数字或字母
temp = (int) (Math.random() * (4) + 1);
switch (temp) {
case 1:
int a = c.math();
code += a;
break;
case 2:
String b = String.valueOf(c.math2());
code += b;
break;
case 3:
String d = String.valueOf(c.math3());
code += d;
break;
case 4:
String e = String.valueOf(c.math4());
code += e;
break;
default:
}
}
System.out.println(code);
Scanner scanner = new Scanner(System.in);
System.out.println("请输入验证码(区分大小写)");
String code2 = scanner.next();
if (code.equals(code2)) {
System.out.println("验证成功");
return true;
} else {
System.out.println("验证码输入失败");
return false;
}
}
}
`
Main类测试
package com.inspur;
/*
在浪*公司的时候没事就整了个验证码生成,项目中可以传到前台进行使用
感觉还有点不完美的地方是没有加密算法,传到前台再进行反转和随机背景
*/
public class Main {
public static void main(String[] args) {
// write your code here
boolean b=Captcha.createCode();
System.out.println(b);
}
}
效果还不错,记录一下