You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.9 KiB
48 lines
1.9 KiB
import java.util.Random;
|
|
|
|
public class MiddleSchoolQuestionStrategy implements QuestionStrategy {
|
|
private final Random random = new Random();
|
|
private final String[] basicOps = {"+", "-", "*", "/"}; // 基本运算符
|
|
|
|
@Override
|
|
public String generateQuestion() {
|
|
// 随机操作数个数 2-5
|
|
int operandsCount = random.nextInt(4) + 2;
|
|
StringBuilder sb = new StringBuilder();
|
|
boolean hasSquareOrRoot = false;
|
|
|
|
// 生成运算符和操作数
|
|
for (int i = 0; i < operandsCount; i++) {
|
|
int num = random.nextInt(100) + 1; // 生成1-100之间的数字
|
|
|
|
// 每个操作数有概率平方或开根号
|
|
if (random.nextBoolean()) {
|
|
if (random.nextBoolean()) {
|
|
sb.append("(").append(num).append(")^2");
|
|
hasSquareOrRoot = true; // 标记是否已经使用了平方或根号
|
|
} else {
|
|
// 确保根号下的数为正
|
|
int rootNumber = random.nextInt(100) + 1; // 始终生成正整数
|
|
sb.append("√(").append(rootNumber).append(")");
|
|
hasSquareOrRoot = true; // 标记是否已经使用了平方或根号
|
|
}
|
|
} else {
|
|
sb.append(num); // 普通数字
|
|
}
|
|
|
|
// 添加运算符(除最后一个操作数外)
|
|
if (i != operandsCount - 1) {
|
|
String op = basicOps[random.nextInt(basicOps.length)];
|
|
sb.append(" ").append(op).append(" ");
|
|
}
|
|
}
|
|
// 如果没有平方或根号,强制添加一个
|
|
if (!hasSquareOrRoot) {
|
|
// 确保根号下的数为正
|
|
int rootNumber = random.nextInt(100) + 1; // 始终生成正整数
|
|
sb.append(" + √(").append(rootNumber).append(")");
|
|
}
|
|
return sb.toString();
|
|
}
|
|
}
|