MathGenerator四则运算方式支持不生成负数结果(pr#1363@Gitee)

This commit is contained in:
Looly
2025-07-02 09:39:10 +08:00
parent f632ddccb2
commit d5bb6b2adb
2 changed files with 18 additions and 4 deletions

View File

@@ -2,9 +2,10 @@
# 🚀Changelog # 🚀Changelog
------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------
# 5.8.40(2025-06-25) # 5.8.40(2025-07-02)
### 🐣新特性 ### 🐣新特性
* 【captcha】 `MathGenerator`四则运算方式支持不生成负数结果pr#1363@Gitee
### 🐞Bug修复 ### 🐞Bug修复
------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------

View File

@@ -16,10 +16,14 @@ public class MathGenerator implements CodeGenerator {
private static final String operators = "+-*"; private static final String operators = "+-*";
/** 参与计算数字最大长度 */ /**
* 参与计算数字最大长度
*/
private final int numberLength; private final int numberLength;
/** 计算结果是否允许负数 */ /**
* 计算结果是否允许负数
*/
private final boolean resultHasNegativeNumber; private final boolean resultHasNegativeNumber;
/** /**
@@ -38,6 +42,15 @@ public class MathGenerator implements CodeGenerator {
this(2, resultHasNegativeNumber); this(2, resultHasNegativeNumber);
} }
/**
* 构造
*
* @param numberLength 参与计算最大数字位数
*/
public MathGenerator(int numberLength) {
this(numberLength, true);
}
/** /**
* 构造 * 构造
* *
@@ -57,7 +70,7 @@ public class MathGenerator implements CodeGenerator {
int numberInt2 = 0; int numberInt2 = 0;
numberInt1 = RandomUtil.randomInt(limit); numberInt1 = RandomUtil.randomInt(limit);
// 如果禁止了结果有负数,且计算方式正好计算为减法,需要第二个数小于第一个数 // 如果禁止了结果有负数,且计算方式正好计算为减法,需要第二个数小于第一个数
if (!resultHasNegativeNumber && CharUtil.equals('-',operator,false)) { if (!resultHasNegativeNumber && CharUtil.equals('-', operator, false)) {
//如果第一个数为0第二个数必须为0随机[0,0)的数字会报错 //如果第一个数为0第二个数必须为0随机[0,0)的数字会报错
numberInt2 = numberInt1 == 0 ? 0 : RandomUtil.randomInt(0, numberInt1); numberInt2 = numberInt1 == 0 ? 0 : RandomUtil.randomInt(0, numberInt1);
} else { } else {