Reputation: 11
I want to process this polynomial
String str = "2*x^2 + x + 2*x^2 + 8 - x^3";
I have split the string with plus and minus operator and got the 2*x^2. I am finding it difficult to work out this operation.
I know first i will need to work out value of x lets say x=2, just don't know how can I parse string to integer as there are other parts of the string to be parsed as well.
do i need to decompose "2*x^2" too?
How do I find * in string. I know i can use str.contains("*"), for this purticular operation i know whats coming after 2*x^2 but if user enters the polynomial thats the tricky bit.
Output is so far
Operation 2*x^2 + x + 2*x^2 + 8 - x^3
Plus Splits
0 2*x^2
1 x
2 2*x^2
3 8 - x^3
Minus Splits
0 2*x^2 + x + 2*x^2 + 8
1 x^3
Upvotes: 1
Views: 1180
Reputation: 100545
In general this operation called "parse an expression" and covered in many books, articles and questions on so like How to parse a mathematical expression given as a string and return a number?.
In this particular case it looks like format is very limited and you can get by with manually splitting string and constructing corresponding data structure:
*
if present.^
.If you can't use regular expression to split strings - use indexOf to find particular characters (like *
in your question - s.indexOf('*')
) and use substring to cut out parts of the string.
As part of building AST for that expression you'll need to How to convert a String to an int in Java? too.
Upvotes: 0
Reputation: 1330
Try to use this: http://projects.congrace.de/exp4j/
Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
.variables("x", "y")
.build()
.setVariable("x", 2.3)
.setVariable("y", 3.14);
double result = e.evaluate();
Upvotes: 2