Arithmetic expression evaluation in java
Computing the value of arithmetic expressions like this one:
( 1 + ( ( 2 + 3 ) * ( 4 * 5 )
Which means multiply 4 by 5, add 3 to 2, multiply the result, and then add 1, you get the value 101.
But how does the Java system do this calculation?
We can address the essential ideas by writing a Java program that can take a string as input (the expression) and produce the number represented by the expression as output.
Dijkstra's Two stack Algorithm for Expression Evaluation
public class ExpressionEvaluation
{
public static void main(String args[]){
Stack<String> ops = new Stack<String>();
Stack<Double> ops = new Stack<Double>();
String s= "( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )";
for(char c : s){
if(c+"".equals("(")) ;
else if(c+"".equals("+")) ops.push(c+"") ;
else if(c+"".equals("-")) ops.push(c+"") ;
else if(c+"".equals("*")) ops.push(c+"") ;
else if(c+"".equals("/")) ops.push(c+"") ;
else if(c+"".equals(")")) {
String op=ops.pop();
double v=vlas.pop();
if(c+"".equals("(")) ;
else if(op.equals("+")) v=vals.pop+v ;
else if(op.equals("-")) v=vals.pop-v ;
else if(op.equals("*")) v=vals.pop*v ;
else if(op.equals("/")) v=vals.pop/v ;
vals.push(v);
}
else vals.push(Double.parseDouble(s));
}
System.out.println(vals.pop());
}
}
The algorithm computes the same value for all of these expressions:
( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
( 1 + ( 5 * ( 4 * 5 ) ) )
( 1 + ( 5 * 20 ) )
( 1 + 100 )
101
Comments
Post a Comment