// PrimaryQueSeting.java package com.example.myapp.service; import com.example.myapp.model.Expression; public class PrimaryQueSeting extends AbstractQuestionSeting { @Override public Expression setQuestion(int count) { if (count == 1) { String expr = getRandomNumber(); return new Expression(expr, parseNumber(expr), null); } int leftCount = 1 + rand.nextInt(count - 1); int rightCount = count - leftCount; Expression left = setQuestion(leftCount); Expression right = setQuestion(rightCount); String op = getRandomOperator(); // 处理除数为0的情况 while (op.equals("/") && Math.abs(right.value) < 1e-10) { right = setQuestion(rightCount); } // 确保减法结果不为负数 if (op.equals("-") && left.value < right.value) { Expression temp = left; left = right; right = temp; } String leftExpr = addParenthesesIfNeeded(left, op, false); String rightExpr = addParenthesesIfNeeded(right, op, true); double value = switch (op) { case "+" -> left.value + right.value; case "-" -> left.value - right.value; case "*" -> left.value * right.value; case "/" -> left.value / right.value; default -> 0; }; return new Expression(leftExpr + " " + op + " " + rightExpr, value, op); } @Override public String addParenthesesIfNeeded(Expression child, String parentOp, boolean isRightChild) { if (child.mainOperator == null) { return child.expression; } int parentPriority = getPriority(parentOp); int childPriority = getPriority(child.mainOperator); if (childPriority < parentPriority) { return "(" + child.expression + ")"; } if (isRightChild && (parentOp.equals("-") || parentOp.equals("/"))) { if (parentPriority == childPriority) { return "(" + child.expression + ")"; } } return child.expression; } }