我正在尝试编写一个Java例程来评估简单的数学表达式,String例如:
"5+3""10-40""10*3"我想避免很多if-then-else语句.我怎样才能做到这一点?
朋友们,
我们正在编写验证框架......
我们有一个如下配置文件...
<root>
<property name="Premium">
<xmlTag>//Message/Request/Product/Benefit/Premium/amount</xmlTag>
<valueType>float</valueType>
<validation condition=">" value="0">Premium Amount cannot be less than Zero.</validation>
</property>
Run Code Online (Sandbox Code Playgroud)
我使用XPath获取XML值并按<valueType>元素值将其转换为float ...
不,我确实value="0"也被转换为浮动.
现在,我必须应用已指定的条件condition=">".
我不想在IF ELSEIF .... ELSE循环上执行此操作.
有没有其他方法将"<"转换为运算符<或在字符串上使用比较运算符?
通过这种方式,我的代码对于未来的更多运营商来说将是简单且有用的.
================================================== ===========================
谢谢大家的建议和答案......
我决定使用BeanShell的bsh.Interpreter.它为我做的工作......
示例代码为您所有...
System.out.println(new bsh.Interpreter().eval("1 < 0"));
System.out.println(new bsh.Interpreter().eval("1 > 0"));
System.out.println(new bsh.Interpreter().eval("1 >= 0"));
System.out.println(new bsh.Interpreter().eval("0 >= 0"));
System.out.println(new bsh.Interpreter().eval("1 != 0"));
System.out.println(new bsh.Interpreter().eval("0 != 0"));
System.out.println(new bsh.Interpreter().eval("1 == 0"));
System.out.println(new bsh.Interpreter().eval("0 == 0"));
Run Code Online (Sandbox Code Playgroud)
归我真假.
谢谢,祝你好运......