简体   繁体   English

计算包含Java中变量的字符串形式的表达式

[英]evaluating an expression in string form containing variables in Java

I have used EvalEx ( https://github.com/uklimaschewski/EvalEx ) and modified it to make a calculator without packages like math . 我已经使用了EvalEx( https://github.com/uklimaschewski/EvalEx )并对其进行了修改,以使其成为没有像Math这样的软件包的计算器。 so now it can get an input in string form from the user and print out the result. 因此,现在它可以从用户那里获取字符串形式的输入并打印出结果。

like this : 像这样 :

Enter an Expression: ADD(DIV(SIN(FACT(3)),CEIL(TAN(MUL(1.5,FIB(4))))),GCD(2,10)) 
The Result is: 1.94    

now the user will enter expressions that contain variables instead of constants 现在用户将输入包含变量而不是常量的表达式

ADD(DIV(SIN(FACT(X1)),CEIL(TAN(MUL(1.5,FIB(X2))))),GCD(Y,10))    

and the overall code should work like below when run : 运行时,总体代码应如下所示:

Enter an Expression: ADD(DIV(SIN(FACT(X1)),CEIL(TAN(MUL(1.5,FIB(X2))))),GCD(Y,10))     
Enter Variables: X1,X2,Y    
Enter values for X1, X2 and Y by this order(separate the values by space): 3 4 2    
The Result is: 1.94        

note that the user first enters the expression then will tell the machine what are the variables (as in " enter variables : x1,x2,y" ) also I have to use objective programming concepts ( so each function of the expression and its constants or variables should be kept as an object ) 请注意,用户首先输入表达式,然后将告诉机器什么是变量(如“输入变量:x1,x2,y”中所示),我也必须使用目标编程概念(因此,表达式的每个函数及其常数或变量应作为对象保存)

so how can I change the existing code from EvalEx to make the program to identify the variables ? 那么如何更改EvalEx的现有代码以使程序识别变量?

You can set up a Map<String, Double> that associates variable names to values, like this: 您可以设置Map<String, Double>将变量名称与值相关联,如下所示:

Map<String, Double> values = new HashMap<String, Double>();
values.put("X", 13.5);
values.put("Y", -3);

Then you can replace all of the variables in the expression by their corresponding values, like this: 然后,您可以将表达式中的所有变量替换为其相应的值,如下所示:

for (Map.Entry<String, Double> entry : values.entrySet())
    expression = expression.replace(entry.getKey(), entry.getValue().toString());

Then you can just apply the method you've already written to expression . 然后,您可以将已经编写的方法应用于expression

This approach is simple, but not very robust. 这种方法很简单,但不是很可靠。 For example, if one of your variable names names is "C" you will mess up the function "CEIL" . 例如,如果您的变量名之一是"C" ,则会使函数"CEIL"混乱。 For this reason, you could insist that all variables begin with "_" or something similar. 因此,您可以坚持所有变量均以"_"或类似名称开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM