从文本文件导入公式

时间:2013-07-22 09:37:19

标签: csv formula

我正在制作一个简单的程序来测试孩子的问题解决技巧,本质上是一个测验,程序从文本文件中提取问题,然后输出问题,并检查用户是否输入了正确答案。

到目前为止,我已将此作为我的文本文件:

David collects 2 comics each month for 3 months. For the next 2 months, he only collects one each month. How many comics does David collect altogether?,8
Sally gives out 4 party bags at the end of her party. Inside each party bag are 5 balloons. How many balloons does Sally give out?,20

然后我将它放入2D数组中,其中[0] [0]是第一个问题,[0] [1]是第一个答案。 这是有效的,但我想使用随机数,这意味着程序必须自己计算答案。这意味着我的文本文件如下所示:

David collects X comics each month for Y months. For the next Z months, he only collects one each month. How many comics does David collect altogether?,((X*Y)+Z)
Sally gives out X party bags at the end of her party. Inside each party bag are Y balloons. How many balloons does Sally give out?,(X*Y)

其中X,Y和Z是随机数,逗号后面的部分是计算答案的公式。要打印出问题,我可以使用if (Question.contains("X")){Question = Question.replace("X", A);},其中A是随机int。但是我如何让Java计算出答案呢?如果我在字符串中有int answer=((X*Y)+Z),我该如何将此字符串转换为代码?我读到Java编译器API可以将字符串更改为可用代码,但这是如何工作的?

由于

1 个答案:

答案 0 :(得分:1)

import javax.script.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("X", 2);
    vars.put("Y", 1);
    vars.put("Z", 3);
    System.out.println("result = "+engine.eval("((X*Y)+Z)", new SimpleBindings(vars)));
 }
}

使用javax.script可以解析并解决简单公式,并生成随机数

(int) (Math.random()*20))应该这样做