修改了四则运算中的部分错误
Grade3QuestionGenerator类
点击查看代码
package qixun;
import java.util.Random;
public class Grade3QuestionGenerator extends Grade2QuestionGenerator {
public Grade3QuestionGenerator() {
this.operandCount = 4; // 操作数不超过4个
this.maxOperandValue = 1000; // 操作数范围不超过1000
}
@Override
public String getQuestion() {
Random random = new Random();
StringBuilder question = new StringBuilder();
// 生成最多4个操作数的表达式
for (int i = 0; i < operandCount - 1; i++) {
int operand = random.nextInt(maxOperandValue) + 1;
String operator = generateOperator(); // 调用父类的 generateOperator()
question.append(operand).append(" ").append(operator).append(" ");
}
question.append(random.nextInt(maxOperandValue) + 1); // 最后一个操作数
return question.toString();
}
@Override
public double getAnswer(String question) {
double result = super.getAnswer(question);
return result;
}
}
点击查看代码
package qixun;
import java.util.Random;
public class Grade4QuestionGenerator extends Grade3QuestionGenerator {
public Grade4QuestionGenerator() {
this.operandCount = 5;
}
@Override
public String getQuestion() {
Random random = new Random();
StringBuilder question = new StringBuilder();
// 可能加入括号
boolean useBrackets = random.nextBoolean();
if (useBrackets) {
question.append("(");
}
for (int i = 0; i < operandCount - 1; i++) {
int operand = random.nextInt(maxOperandValue) + 1;
String operator = generateOperator();
question.append(operand).append(" ").append(operator).append(" ");
// 添加括号
if (useBrackets && i == 2) {
question.append("(").append(random.nextInt(maxOperandValue) + 1).append(") ");
useBrackets = false; // 防止括号重复使用
}
}
question.append(random.nextInt(maxOperandValue) + 1); // 最后一个操作数
if (useBrackets) {
question.append(")"); // 如果还未关闭括号,添加关闭括号
}
return question.toString().trim(); // 去掉多余空格
}
}