# math expression parser

• 05-18-2010, 05:17 PM
Egrimm86
math expression parser
Hi all!
I'm an italian student, and I have to program a parser wich have to reconize if a string is an algebrical expressione and pass his result to an evaluatoer that have to clculate the result of the expression.

Mine idea is to divide the expression in OpExp. An OpExp is composed of an operator and what he have on his right and his left.

Code:

```public class OpExp {         private String operator;         private IExp l_IExp;         private IExp r_IExp;         public OpExp(String op, IExp left, IExp right){                 operator = op;                 l_IExp = left;                 r_IExp = right;         }         public void finalize() throws Throwable {                 super.finalize();         }         public IExp getLeft(){                 return l_IExp;         }         public String getOpName(){                 return operator;                         }         public IExp getRight(){                 return r_IExp;         } }```
We choose to use a stack stack, but, if the order of the operation is good, the order of wich is on left or right is often wrong.

For example, in the expression (3+2)+2*(5+6), when he have to calculate the product of "*" on the left he see (3+2) and not the "2" wich is at the bottom of the stack... so probably the problem is that we use only a stack... maybe with 2 stack or a list...

If it's useful, I could post the code of ours parser

Any suggestion?
• 05-19-2010, 07:24 AM
r035198x
1.) Please get rid of that finalize method.
2.) Are you restricting yourself to binary operators only?
3.) There is obviously something wrong your implementation if you are not seeing some of the input.
• 05-19-2010, 08:41 AM
JosAH
Quote:

Originally Posted by Egrimm86
Code:

```public class OpExp {         private String operator;         private IExp l_IExp;         private IExp r_IExp;         public OpExp(String op, IExp left, IExp right){                 operator = op;                 l_IExp = left;                 r_IExp = right;         }         public void finalize() throws Throwable {                 super.finalize();         }         public IExp getLeft(){                 return l_IExp;         }         public String getOpName(){                 return operator;                         }         public IExp getRight(){                 return r_IExp;         } }```

Can an IExp be an OPExp? If not your types are incorrect, e.g. the right side of the OPExp 2*(5+6) needs to be an OPExp itself (5+6).

kind regards,

Jos
• 05-19-2010, 09:41 PM
Egrimm86
Thanks for the answers, maybe I found the solution.