You are on page 1of 3

import java.util.Scanner; import java.util.

Stack; /** * * @author Joaquim Ribeiro */ public class Postfix { //the code looks clean, but could be optimized by removing extra comparisons , eg isOperator()... public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Example conversion : ( 4 + 8 ) * ( 6 - 5 ) / ( ( 3 2 ) * ( 2 + 2 ) ) --> "+toPostfix("( 4 + 8 ) * ( 6 - 5 ) / ( ( 3 - 2 ) * ( 2 + 2 ) )")); System.out.print("\nEnter an expression (Leave a space in between)\n> ") ; String infix = scanner.nextLine(); String postfix = toPostfix(infix); System.out.println(postfix); System.out.println(eval(postfix)); } public static double eval(String postfix) { Stack<String> stack = new Stack<String>(); String[] expr = postfix.split(" "); double op1 = 0; double op2 = 0; for (int i = 0; i < expr.length; i++) { String s = expr[i]; if (isOperand(s)) { stack.push(s); } else if (isOperator(s)) { op2 = Double.parseDouble(stack.pop()); op1 = Double.parseDouble(stack.pop()); if (s.equals("+")) { stack.push(Double.toString(op1+op2)); } else if (s.equals("-")) { stack.push(Double.toString(op1-op2)); } else if (s.equals("*")) { stack.push(Double.toString(op1*op2)); } else if (s.equals("/"))

{ stack.push(Double.toString(op1/op2)); } } else { throw new UnsupportedOperationException("Unsupported character " +s+" at index "+i); } } return Double.parseDouble(stack.pop()); } public static String toPostfix(String infix) { Stack<String> stack = new Stack<String>(); String postfix = ""; String[] expr = infix.split("\\s"); for (int i = 0; i < expr.length; i++) { String c = expr[i]; String o = ""; if (isOperand(c)) { postfix += c+" "; } else if (isOperator(c)) { while (stack.isEmpty() == false) { o = stack.pop(); if (isHigher(c, o)) { stack.push(o); break; } postfix += o+" "; } stack.push(c); } else if (isParen(c)) { if (c.equals(")")) { while (stack.isEmpty() == false) { o = stack.pop(); if (o.equals("(")) { break; } postfix += o+" "; } } else

stack.push(c); } else { throw new UnsupportedOperationException("Unsupported character " +c+" at index "+i); } //System.out.println("Stack: "+stack); //System.out.println("Postfix: "+postfix); } while (stack.isEmpty() == false) { String o = stack.pop(); postfix += o+" "; } return postfix; } public static boolean isOperand(String op) { try { Double.parseDouble(op); return true; } catch(NumberFormatException nfe) { return false; } } public static boolean isOperator(String op) { return op.equals("+") || op.equals("-") || op.equals("*") || op.equals(" /"); } public static boolean isHigher(String op1, String op2) { if (op1.equals("*") || op1.equals("/")) if (op2.equals("+") || op2.equals("-")) return true; if (op1.equals("*") || op1.equals("/") || op1.equals("+") || op1.equals( "-")) if (op2.equals("(")) return true; return false; } public static boolean isParen(String str) { return str.equals("(") || str.equals(")"); } }

You might also like