

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Java Program to convert a String to int
- Java Program to convert int to binary string
- Java Program to convert int to Octal String
- Convert String to Java int
- Java Program to convert an int value to String
- Convert int to String in Java
- How to convert int to String in java?
- Java Program to convert int array to IntStream
- How to convert a Java String to an Int?
- Java Program to evaluate mathematical expressions in String
- How to convert a String into int in Java?
- How to convert a String to an int in Java
- MongoDB query to convert string to int?
- How to convert int to string in Python?
- Java Program to convert positive int to negative and negative to positive
Advertisements