Sunteți pe pagina 1din 2

https://www.cs.duke.edu/courses/cps100/fall09/code/Postfix.

java

import java.util.*; /** * Simple illustration of postfix evaluation using * StringTokenizer, Stack, and Exceptions. * @author Owen Astrachan * @date revised Oct 7, 2009 * original from 2004 */ public class Postfix { private static final String DELIMS = "+-*/ "; private int operate(String op, int lhs, int rhs){ if (op.equals("+")) { return lhs + rhs; } if (op.equals("*")){ return lhs * rhs; } if (op.equals("-")){ return lhs - rhs; } if (op.equals("/")){ return lhs / rhs; } throw new IllegalArgumentException("unrecognized operator "+op); } public int evaluate(String s){ Stack<String> stack = new Stack<String>(); StringTokenizer tokens = new StringTokenizer(s,DELIMS,true); try { while (tokens.hasMoreTokens()){ String t = tokens.nextToken(); if (DELIMS.indexOf(t) >= 0){ if (t.equals(" ")) continue; int right = Integer.parseInt(stack.pop()); int left = Integer.parseInt(stack.pop()); stack.push(""+operate(t,left,right)); } else { stack.push(t); } } } catch (NumberFormatException e) { throw new RuntimeException("badly formed postfix expression "+e); } catch (EmptyStackException ese){ throw new RuntimeException("empty stack error "+ese); } int result = Integer.parseInt(stack.pop()); if (stack.size() > 0){ throw new IllegalArgumentException("non empty stack on "+s); } return result; } public void readLoop(){ Scanner in = new Scanner(System.in); String line;

1 of 2

9/11/2013 4:15 PM

https://www.cs.duke.edu/courses/cps100/fall09/code/Postfix.java

while (in.hasNextLine()){ line = in.nextLine(); try { int result = evaluate(line); System.out.printf("value of %s = %d\n", line,result); } catch (Exception e){ System.out.printf("error: %s\n",e); } } } public static void main(String[] args){ Postfix p = new Postfix(); p.readLoop(); } }

2 of 2

9/11/2013 4:15 PM

S-ar putea să vă placă și