我正在制作一个简单的程序来测试孩子们解决问题的能力,本质上是一个测验,程序从文本文件中提取一个问题,然后打印这些问题,并检查用户是否输入了正确的答案。
到目前为止,我已经把它作为我的文本文件:
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
然后我把它放到一个二维数组中,其中 [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);}
where A is a random int。但是我怎样才能让 Java 计算出答案呢?如果我有int answer=((X*Y)+Z)
一个字符串,我该如何将此字符串转换为代码?我读到 Java Compiler API 可以将字符串更改为可用代码,但这是如何工作的?
谢谢