- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to convert mathematical string to int
To evaluate mathematical string to int, use Nashorn JavaScript in Java i.e. scripting. Nashorn invoke dynamics feature, introduced in Java 7 to improve performance.
For scripting, use the ScriptEngineManager class for the engine:
ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");
Now, use put() to set a key/value pair in the state of the ScriptEngine:
scriptEngine.put("one", 10); scriptEngine.put("two", 50); scriptEngine.put("three", 40);
Now, here is the mathematical string. Use eval to evaluate:
String strExp = "(one + two - three) == 20"; Object evalExp = scriptEngine.eval(strExp);
Example
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Demo { public static void main(String[] args) { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn"); scriptEngine.put("one", 10); scriptEngine.put("two", 50); scriptEngine.put("three", 40); try { String strExp = "(one + two - three) == 20"; Object evalExp = scriptEngine.eval(strExp); System.out.println("Is "+strExp + " ? " + evalExp); } catch (ScriptException se) { se.printStackTrace(); } } }
Output
Is (one + two - three) == 20 ? true
Advertisements