parent
34070e2c0a
commit
343b4b4ef6
@ -1,46 +0,0 @@
|
||||
import java.util.Random;
|
||||
|
||||
public abstract class AbstractQuestionSeting implements QuestionSeting{
|
||||
static Random rand = new Random();
|
||||
|
||||
public String getRandOpe(){
|
||||
String[] operators= {"+","-","*","/"};
|
||||
int index = rand.nextInt(4);
|
||||
return operators[index];
|
||||
}
|
||||
public String getRandnum(){
|
||||
int num = rand.nextInt(1,100);
|
||||
return String.valueOf(num);
|
||||
}
|
||||
// 定义运算符优先级
|
||||
public int getPriority(String op) {
|
||||
if (op == null) return -1; // 叶子节点(数字)
|
||||
if (op.equals("+") || op.equals("-")) return 1;
|
||||
if (op.equals("*") || op.equals("/")) return 2;
|
||||
return 0;
|
||||
}
|
||||
|
||||
public String addParenthesesIfNeeded(Expr 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; // 其他情况不用括号
|
||||
}
|
||||
}
|
||||
Loading…
Reference in new issue