Java String来完成数学总和 [英] Java String to complete mathematical sum
问题描述
在java中,我目前正在尝试通过在JTextField中键入文本,将其放入String并将其转换为int并求解来找到一种方法来进行数学求和。但问题是,我不想简单地将数字放入字符串中,而是将实际的总和包括加法,减法等。
In java, I am currently in the process of trying to find a way to do mathematical sums by typing in text to a JTextField, putting it into a String, and converting it to an int and solving. The problem is however, I don't want to simply put a number into the string but an actual sum including addition, subtraction etc.
目前它只接受类似的操作,1将从字符串转换为int,但当我执行'1 + 1'或甚至只是'1+'时,它会抛出异常,因为' +'不是数字。
我已经明白它不会工作因为int只允许数字。
Currently it will accept just doing something like, 1 which will go from string and convert to an int, but when I do '1+1' or even just '1+' it throws exceptions everywhere because '+' isn't a number.
Which I already understand that it wont work because int's only allow numbers.
我有办法吗?安全地在文本字段中输入一个完整的总和并以某种方式将其转换为int?比如输入7-2 * 5然后答案被保存在一个int?
Is there a way I can safely type a complete sum into the text field and convert it to an int somehow? Like typing 7-2*5 and then the answer being held in an int?
谢谢。
推荐答案
您可以使用 JavaScript
引擎:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String expression = textField.getText();
System.out.println(engine.eval(expression));
编辑以允许所有公式:
现在你要做的就是允许 sin,cos,tan 这样的事情:
All you have to do now to allow things like sin, cos, tan is this:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String expression = textField.getText();
// Between here...
expression = expression.
replace("sin", "Math.sin").
replace("cos", "Math.cos").
replace("tan", "Math.tan").
replace("sqrt", "Math.sqrt").
replace("log", "Math.log").
replace("pi", "Math.PI");
// And so on...
System.out.println(engine.eval(foo));
那么你可以这样做:
5 + 5 - 2 / 5 + sin(55) - log(20)
你想要的任何东西。
这篇关于Java String来完成数学总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!