- Trending Categories
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
- Related Articles
- Java Program to convert a String to int
- Java Program to convert int to binary string
- Java Program to convert int to Octal String
- Java Program to convert an int value to String
- Convert String to Java int
- Convert int to String in Java
- How to convert int to String in java?
- Golang Program to convert int type variables to String
- Swift Program to convert int type variable to string
- How to convert a Java String to an Int?
- Java Program to convert int array to IntStream
- Java Program to evaluate mathematical expressions in String
- How to convert a String to an int in Java
- Golang Program to convert string type variables into int
- C++ Program to Convert int Type Variables into String

Advertisements