Postfix Expression Evaluation Program
Write a program to evaluate a postfix expression using stack
-------------------------Program---------------------------------------
import java.util.Stack; public class PostfixEvaluation { private static String postfixExpr; public PostfixEvaluation(String postfix) { this.postfixExpr= postfix; } /** * Evaluate postfix expression * * @param postfix The postfix expression */ public Double evaluate() { Stack s = new Stack(); Double result = 0.0; String operand = ""; for(int i = 0; i<postfixExpr.length();i++){ if(Character.isDigit(postfixExpr.charAt(i)) == true || ( postfixExpr.charAt(i)=='-' ) ){ if( postfixExpr.charAt(i)=='-' && i!=postfixExpr.length()-2 && i!=postfixExpr.length()-1) { if( Character.isDigit(postfixExpr.charAt(i+1)) && Character.isDigit(postfixExpr.charAt(i+1)) == true) { operand="-"; i++; } } if ( postfixExpr.charAt(i)!='-' ) { operand = operand + postfixExpr.charAt(i); if(Character.isDigit(postfixExpr.charAt(i+1)) == false){ s.push(operand); operand = ""; } } } if(postfixExpr.charAt(i) == '+'){ Double x = Double.parseDouble((String) s.pop()) + Double.parseDouble((String) s.pop()); result = x ; s.push(String.valueOf(x)); } if(postfixExpr.charAt(i) == '-'){ Double p =Double.parseDouble((String) s.pop()); Double q =Double.parseDouble((String) s.pop()); Double x = p-q; result = x ; s.push(String.valueOf(x)); } if(postfixExpr.charAt(i) == '*'){ Double x = Double.parseDouble((String) s.pop()) * Double.parseDouble((String) s.pop()); result = x ; s.push(String.valueOf(x)); } if(postfixExpr.charAt(i) == '/'){ Double p =Double.parseDouble((String) s.pop()); Double q =Double.parseDouble((String) s.pop()); if(q!=0){ Double x = p/q; result = x ; s.push(String.valueOf(x)); } else { throw new ArithmeticException("Division by zero error"); } } } return result; } // public static void main(String[] args) { // String postfix = "3 2 /"; // // String output; // // PostfixEvaluation pfe = new PostfixEvaluation(postfix); // // Double value = pfe.evaluate(); // System.out.println(value); // // } }
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment