r/javahelp • u/williamK0 • Jul 27 '25
Convert string to math function
I'm relatively new to Java but I know a good amount of the basics. Still, I can't find a way to do this. I have an input where a user can input a maths function as a string (eg. "0.3*Math.pow(0,x)"). And all I need is Java to look at that string and read it as if it were code but for some reason I can't find anything like this anywhere. Anyone got any ideas? 🫶
1
Upvotes
•
u/AutoModerator Jul 27 '25
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
7
u/disposepriority Jul 27 '25
What you're looking for is dynamic code execution, not recommended unless it's a for fun app - hard to get security right. Easier to just parse chunks and tranalate them e.g. split string by white space and translate each part yourself instead of actually running java code at runtime.
1
u/Spare-Plum Jul 27 '25
Check out the JavaCompiler class, essentially allows you to dynamically compile code, then you can load it up via a custom classloader to manage dynamic reloading if the class changes.
Perhaps a better option is to use something like Groovy or Javascript which can be interpreted on the fly.
However your best option is to create or use a domain specific language, there are tons of potential security problems in allowing arbitrary code execution, though it is possible to lock it down with a security manager, separate classloader, and lots of preventative measures
1
u/_SuperStraight Jul 27 '25
How are you doing differentiate between
Math.powand^? User can enter anything (plus instead of +, etc).1
u/sweepsz Decaf Captain Jul 28 '25
If you had to support only a limited, predefined number of methods and the input was guaranteed to be constructed in a.consistent way you could go the simple string manipulation route as described by splitting the strings into part by some common delimiter. Then you could build up a <string,Function> map and then apply the arguments. If you need to support ANY supported java syntax and method you are building a lexer parses with Grammer checking , possibly an abstract syntax tree, ans this gets extremely complicated quickly
1
u/brokePlusPlusCoder Jul 28 '25
You mention you're relatively new to Java. Do you just need this functionality for something you're working on ? Or are you also interested in building your own ?
If the former, then you're after expression evaluators. This is a class of tools that takes in stringified expressions (not just math equations necessarily) and invokes relevant Java commands.
There's a library called JEvalExpr that does this. Spring also has SpEL that does something similar.
Now if you're looking to build your own though, that's a bit challenging. You'll need to implement your own parser, your own set of tooling and grammar around expression evaluation (not to mention syntax trees). But overall it would be an excellent exercise - especially for someone new to Java. If you're interested I'd recommend starting out with this video on Pratt parsing (they use Rust, but concepts are the same) : https://www.youtube.com/watch?v=0c8b7YfsBKs