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.
test-paper-system/src/PrimaryMaker.java

79 lines
2.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package Program;
public class PrimaryMaker extends QuestionMaker {
private static final char[] operators = {'+', '-', '*', '/'};
/**
* 添加括号
* @param expression 原式
* @return 添加括号后的式子
*/
protected String BracketsMaker(String expression){
String[] sum = expression.split(" ");
// 只有当式子长度>=5时才添加括号
if(sum.length >= 5){
int maxStart = (sum.length - 5) / 2;
if(maxStart > 0){
int start = (rand.nextInt(maxStart) + 1) * 2;
int minEnd = start + 2;
int maxEnd = Math.min(sum.length - 3, start + 4);
if(maxEnd > minEnd){
int end = minEnd + (rand.nextInt((maxEnd - minEnd) / 2 + 1)) * 2;
StringBuilder result = getBuilder(sum, start, end);
return result.toString();
}
}
// 如果上述逻辑没有添加括号,强制在前三个元素周围添加括号
StringBuilder result = new StringBuilder();
result.append("(").append(sum[0]).append(" ").append(sum[1]).append(" ").append(sum[2]).append(")");
for(int i = 3; i < sum.length; i++){
result.append(" ").append(sum[i]);
}
return result.toString();
}
// 对于长度<5的短式直接返回原式不添加括号
return expression;
}
private static StringBuilder getBuilder(String[] sum, int start, int end) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < sum.length; i++){
if(i == start){
result.append("(");
}
result.append(sum[i]);
if(i == end){
result.append(")");
}
if(i < sum.length - 1){
result.append(" ");
}
}
return result;
}
@Override
protected String makeOneQuestion() {
int count = rand.nextInt(4) + 2;
StringBuilder question = new StringBuilder();
question.append(randomMaker());
for(int i = 1; i < count; i++){
char operator = operators[rand.nextInt(operators.length)];
int randNum = randomMaker();
question.append(" ").append(operator).append(" ").append(randNum);
}
return BracketsMaker(question.toString());
}
@Override
protected boolean checkQuestion(String question) {
return question.matches("[0-9+\\-*/() ]+");
}
}