java 加减法验证码
时间: 2023-08-09 08:04:44 浏览: 133
以下是一个简单的 Java 加减法验证码生成器:
```java
import java.util.Random;
public class CaptchaGenerator {
private static final int MIN_NUM = 1;
private static final int MAX_NUM = 10;
private static final String[] OPERATORS = {"+", "-"};
public static String generate() {
Random random = new Random();
int num1 = random.nextInt(MAX_NUM - MIN_NUM + 1) + MIN_NUM;
int num2 = random.nextInt(MAX_NUM - MIN_NUM + 1) + MIN_NUM;
String operator = OPERATORS[random.nextInt(OPERATORS.length)];
int result;
String captcha;
if (operator.equals("+")) {
result = num1 + num2;
captcha = num1 + " + " + num2 + " = ?";
} else {
result = num1 - num2;
captcha = num1 + " - " + num2 + " = ?";
}
captcha += " " + result;
return captcha;
}
}
```
使用方法:
```java
String captcha = CaptchaGenerator.generate();
```
该代码会生成一个形如 "2 + 3 = ? 5" 的字符串作为验证码,其中 "?" 部分需要用户输入计算结果。
阅读全文