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.
28 lines
1014 B
28 lines
1014 B
package question;
|
|
|
|
import java.util.Random;
|
|
|
|
public class MiddleQuestionGenerator implements QuestionGenerator {
|
|
private static final Random random = new Random();
|
|
private final QuestionGenerator primaryGenerator = new PrimaryQuestionGenerator();
|
|
|
|
@Override
|
|
public Question generateQuestion() {
|
|
Question q = primaryGenerator.generateQuestion();
|
|
if (random.nextBoolean()) {
|
|
return new Question(q.getQuestion() + " ^ 2", evaluate(q.getQuestion() + "^2"));
|
|
} else {
|
|
return new Question("√" + q.getQuestion(), evaluate("Math.sqrt(" + q.getQuestion() + ")"));
|
|
}
|
|
}
|
|
|
|
private String evaluate(String expr) {
|
|
try {
|
|
javax.script.ScriptEngineManager mgr = new javax.script.ScriptEngineManager();
|
|
javax.script.ScriptEngine engine = mgr.getEngineByName("JavaScript");
|
|
return String.valueOf(engine.eval(expr.replace("^", "**")));
|
|
} catch (Exception e) {
|
|
return "?";
|
|
}
|
|
}
|
|
} |