If the expression is in the form of a string, then we generally encounter big problems in evaluating.
Here is a method that directly calls JavaScript to return the value, which is undoubtedly a magical tool.
The code is as follows:
package scc;import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;import javax.script.ScriptException;public class Counter {public static void main(String[] args) {// TODO Auto-generated method stubScriptEngineManager manager = new ScriptEngineManager();ScriptEngine SE = manager.getEngineByName("js");String Numbers = new String("1+2/5");try {String ans = SE.eval(Numbers).toString();System.out.println(ans);}catch (ScriptException e) {e.printStackTrace();}}}I will share a simple operation of implementing calculator in Java. The code is as follows:
ScriptEngineManger sem = new ScriptEngineManger();/*script engine management*/ScriptEngine se= sem.getEngineByName("JavaScript");/*script engine*/JTextField tf = new JTextField(10);try {System.out.println (se.eval ("2+2"));/* Execute a script print result*/tf.setText(se.eval(tf.getText()).tostring);//Show the operation result to the text box, similar to the timer effect}catch (ScriptException e) {System.out.println ("Arithmetic error!");}Summarize
The above is the entire content of this article about Java calling JavaScript to implement string calculator code examples. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!