I want to evaluate a sting math expression in java. This string should contain functions (avg, max, min, ...) applied to vectors or simple numbers. I already use ScriptEngineManager with javasript engine but it just use numbers. I also see symja lib but it look too complicated et not documented. How to do? Thanks
How to evaluate string math expression in java
1.3k Views Asked by Fridolin Amadou At
2
There are 2 best solutions below
0
Michael Couck
On
There are two very good expression parsers, JEP(paid now unfortunately - http://www.singularsys.com/jep/) and Jexl(much more than just an expression parser - http://commons.apache.org/proper/commons-jexl/).
I prefer Jexl, so here is an example:
JexlEngine jexl = new JexlEngine();
// The expression to evaluate
Expression e = jexl.createExpression("((a || b) || !c) && !(d && e)");
// Populate the context
JexlContext context = new MapContext();
context.set("a", true);
context.set("b", true);
context.set("c", true);
context.set("d", true);
context.set("e", true);
// Work it out
Object result = e.evaluate(context);
More examples - http://commons.apache.org/proper/commons-jexl/reference/examples.html
Related Questions in JAVA
- I need the BIRT.war that is compatible with Java 17 and Tomcat 10
- Creating global Class holder
- No method found for class java.lang.String in Kafka
- Issue edit a jtable with a pictures
- getting error when trying to launch kotlin jar file that use supabase "java.lang.NoClassDefFoundError"
- Does the && (logical AND) operator have a higher precedence than || (logical OR) operator in Java?
- Mixed color rendering in a JTable
- HTTPS configuration in Spring Boot, server returning timeout
- How to use Layout to create textfields which dont increase in size?
- Function for making the code wait in javafx
- How to create beans of the same class for multiple template parameters in Spring
- How could you print a specific String from an array with the values of an array from a double array on the same line, using iteration to print all?
- org.telegram.telegrambots.meta.exceptions.TelegramApiException: Bot token and username can't be empty
- Accessing Secret Variables in Classic Pipelines through Java app in Azure DevOps
- Postgres && statement Error in Mybatis Mapper?
Related Questions in STRING
- What does: "char *argv[]" mean?
- User input sanitization program, which takes a specific amount of arguments and passes the execution to a bash script
- JSON Body is Not Passing Certain Strings
- Regex to match repeated substring in Google Sheets
- Find the sum of the numbers in the sequence
- Hello, how can I use a block parameter of withstyle parameter when we create a annotated string in jetpackpack compose
- How to convert an HTML string to an escaped one?
- Quintic Number Number Counting Hash Function
- From Buffer("string", "hex) to string JS
- Calling ToString with a nominated format returns Char rather than String
- How to update an already existing array by accessing it by a variable with the exact same name assigned to it
- Why does \b not interpreted as backslash in this regular expression
- Python: why aren’t strings being internalized if they are received from ints by using str()?
- If the element(s) in the first list equal element(s) of the second list, replace with element(s) of the third list
- About Suffix Trees features
Related Questions in MATH
- How to restrict vpasolve() to only integer solutions (MATLAB)
- Need clarification on VHDL expressions involving std_logic_vector, unsigned and literals, unsure about compiler interpretation
- What is the algorithm behind math.gcd and why it is faster Euclidean algorithm?
- How to throw a charged particle in a electric vector field?
- Issues with a rotation gizmo and sign flips when converting back to euler angles
- Solving the area of a 2 dimensional shape
- WorldToScreen function
- Algorithm to find neighbours of point by distance with no repeats
- Detecting Circles and Ellipses from Point Arrays in Java
- three parameter log normal distribution
- Bound for product of matrices
- Javascript animation taking incorrect amount of time to reach desired location
- Converting Math.js-like Expressions to Runnable Python Code
- Looking for a standard mathematical function that returns 0 if x = 0 and a constant k when x <> 0
- Partitions in co-lexicographic order (PARI/GP algorithm without recursion)
Related Questions in SCRIPTENGINE
- Why is engine is null or I need to download library
- How Java & GraalJs ScriptEngine interact with variables
- Android: How to access the text produced by website scripts
- getEngineFactories() returns an empty list
- ScriptEngine is always null
- Springboot server-side chart creation
- How do I run Python Scripts in Java with the ScriptEngine?
- Run Python with imports via java ScriptEngineManager
- How do I remove ScriptObjectMirror(jdk.nashorn.api.scripting.ScriptObjectMirror) since it is Deprecated?
- ScriptEngine reusing arguments?
- Decoding Base64 String in Java
- Use Javascript scripting engine in Java 17
- How to run python script from C# code by using command
- Roslyn throws exception 'Item' is not declared. It may be inaccessible due to its protection level
- ScriptEngine in android studio
Related Questions in SYMJA
- Java Equation Evaluation
- App crashes when using Symja library for symbolic differentiation of a user input function. (Using Android Studio)
- How does the library "Symja" need to be imported with Gradle in order to work with the Elasticsearch server module?
- How to fix precision in Symja?
- How to solve multivariate equation systems programmatically?
- Gradle build stuck while using symja library
- Android dependency Symja will not load in gradle
- Abs[x] not recognized in symja math parser
- Gradle build slow after adding symja and log4j-1.2.11 to Android studio
- symja: quadratic inequation and modulus
- How to evaluate string math expression in java
- Symja Jar Algebra
- How to solve inequalities with Symja?
- Proper symja evaluation?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Take a look at the Math and String classes of the javadoc. If you know the format of the string, you should be able to search through it to find the specific numbers and functions you're using. If you are only using one of the avg/max/min per input, it should be pretty easy.
Here's an example, lets say you want it formatted like so (it's easy if theres a comma after every value):
"FUNCTION(a, b, c,)" -> "MIN(3,6,8,)"
The first thing you want to do is have it figure out which function you're doing. Using the indexOf method, we can figure out if it contains MIN or MAX or whatever.
You'll also need to create a list of all the numbers you're using.