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.
31 lines
972 B
31 lines
972 B
package com.personalproject.generator;
|
|
|
|
import java.util.Random;
|
|
|
|
/**
|
|
* 生成包含基础四则运算的小学难度题目表达式.
|
|
*/
|
|
public final class PrimaryQuestionGenerator implements QuestionGenerator {
|
|
private static final String[] OPERATORS = {"+", "-", "*", "/"};
|
|
|
|
@Override
|
|
public String generateQuestion(Random random) {
|
|
// 至少生成两个操作数,避免题目退化成单个数字
|
|
int operandCount = random.nextInt(4) + 2;
|
|
StringBuilder builder = new StringBuilder();
|
|
for (int index = 0; index < operandCount; index++) {
|
|
if (index > 0) {
|
|
String operator = OPERATORS[random.nextInt(OPERATORS.length)];
|
|
builder.append(' ').append(operator).append(' ');
|
|
}
|
|
int value = random.nextInt(100) + 1;
|
|
builder.append(value);
|
|
}
|
|
String expression = builder.toString();
|
|
if (operandCount > 1 && random.nextBoolean()) {
|
|
return '(' + expression + ')';
|
|
}
|
|
return expression;
|
|
}
|
|
}
|