I have a string like 3x^2+5X+7 and what I want to do is, get x value from the user and make the program solve this equation. I couldn't figure it out how I am gonna do this so far. I would be really glad if you help me.
Asked
Active
Viewed 163 times
-4
-
take a look at this https://www.objecthunter.net/exp4j/ – Ahmed.ess Nov 14 '19 at 14:58
-
Create a stack of characters, Put all Chars to that stack now you need to get the priority of each traversing on the stack – Basil Battikhi Nov 14 '19 at 15:00
-
Add code snippet to here for discussing your approach and let us see what is wrong on your code then you can request help for non-working states or lines. – oguzhan00 Nov 14 '19 at 15:02
-
Please see: [Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/q/284236) – EJoshuaS - Stand with Ukraine Nov 14 '19 at 15:14
1 Answers
4
You could try this:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
int x = 42;
String foo = "3*x^2+5*x+7";
String input = foo.replaceAll("x", x);
System.out.println(engine.eval(foo));

Adriaan Koster
- 15,870
- 5
- 45
- 60