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.

73 lines
2.4 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.

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class JuniorQuestionGenerator extends AbstractQuestionGenerator {
private static final String[] OPERATORS = {"+", "-", "×", "÷"};
private static final String[] ADVANCED_OPS = {"²", "√"};
@Override
public String generateQuestion(int operandCount, Random random) {
String advancedOp = ADVANCED_OPS[random.nextInt(ADVANCED_OPS.length)];
if (advancedOp.equals("²")) {
return generateWithSquare(operandCount, random);
} else {
return generateWithSquareRoot(operandCount, random);
}
}
private String generateWithSquare(int operandCount, Random random) {
String baseExpression = generateBasicExpression(operandCount, random, OPERATORS);
// 修正:用空格连接,保持格式
String[] parts = baseExpression.split(" ");
int squarePos = findNumberPosition(parts);
if (squarePos >= 0) {
parts[squarePos] = parts[squarePos] + "²";
}
return String.join(" ", parts); // 修正:用空格连接
}
private String generateWithSquareRoot(int operandCount, Random random) {
StringBuilder question = new StringBuilder();
question.append("√").append(random.nextInt(MAX_OPERAND) + MIN_OPERAND); // 修正应该是√而不是v
if (operandCount > 1) {
String remainingExpression = generateBasicExpression(operandCount - 1, random, OPERATORS);
String[] parts = remainingExpression.split(" ", 2);
if (parts.length > 1) {
question.append(" ").append(parts[1]);
}
}
return question.toString();
}
private int findNumberPosition(String[] parts) {
List<Integer> numberPositions = new ArrayList<>();
for (int i = 0; i < parts.length; i++) {
if (isNumber(parts[i])) {
numberPositions.add(i);
}
}
return numberPositions.isEmpty() ? -1 : numberPositions.get(new Random().nextInt(numberPositions.size()));
}
private boolean isNumber(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public String getQuestionType() {
return "初中";
}
}