2013-07-22 45 views
1

我正在製作一個簡單的程序,它將測試兒童的問題解決技能,本質上是一個測驗,其中程序從文本文件中提取問題,然後打印出問題並檢查用戶輸入正確的答案。從文本文件導入公式

到目前爲止,我有這個作爲我的文本文件:

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);}其中A是一個隨機int。但是我怎樣才能讓Java計算出答案呢?如果我在字符串中有int answer=((X*Y)+Z),我該如何將此字符串轉換爲代碼?我讀過Java Compiler API可以將字符串更改爲可用的代碼,但這是如何工作的?

感謝

回答

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))應該這樣做

+0

這是完美的,謝謝。爲了創建隨機數,我通常使用'int a = random.nextInt(10)',這和你提到的'(int)(Math.random()* 20))有什麼區別? –

+0

它基本上是一樣的,除非你對線程安全感興趣,並且分配的不一致性,任何給你隨機的方法都應該這樣做。主要區別在於math.random是線程安全的,兩者的用法還有其他差異,但只有當您生成非常大的數字集並且希望分佈均勻時纔是重要的。 – user1820801