100 likes | 185 Views
CS 220 Fall 2013. Postfix and Infix Expressions. ExpEvalGUI. Postfix Eval. public String postEval(String e) { Stack<Integer> s = new Stack<Integer>(); Token op; MyScanner scan = new MyScanner(e); while ((op = scan.next()) != null) { System. out.println(op.tok);
E N D
CS 220 Fall 2013 Postfix and Infix Expressions
Postfix Eval public String postEval(String e) { Stack<Integer> s = new Stack<Integer>(); Token op; MyScanner scan = new MyScanner(e); while ((op = scan.next()) != null) { System.out.println(op.tok); if (op.isInt()) s.push(op.intVal()); else if (op.isOperator() && s.size() > 1) doOp(op.operator(), s); else return "Illegal Expression"; } if (s.size() == 1) return ""+s.pop(); else return "Illegal Expression"; }
doOP private void doOp(char op, Stack<Integer> s) { int k = 0; int i = s.pop(); int j = s.pop(); switch (op) { case '*': k = i*j; break; case '/' : k = j/i; break; case '+' : k = i+j; break; case '-': k = j-i; break; case '%': k = j%i; break; case '^': k = (int) Math.pow(j,i); } s.push(k); }
MyScanner public class MyScanner { String exp; int position; public MyScanner(String e) { exp = e; position = 0; }
MyScanner public Token next() { while (position < exp.length() && exp.charAt(position) == ' ') position++; if (position >= exp.length()) return null; char ch = exp.charAt(position); if (Character.isDigit(ch)) { String tok = ""+ch;; position++; while (position < exp.length() && Character.isDigit(exp.charAt(position)) ) { tok = tok+exp.charAt(position); position++; } return new Token(tok, true); }
MyScanner else if ((new String("+-*/^%()")).indexOf(ch) != -1) { position++; return new Token(""+ch, false); } else return null; } }
Token public class Token { String tok; boolean isInt; public Token(String e, boolean b) { tok = e; isInt = b; } public boolean isInt() { return isInt; }
Token public int intVal() { return Integer.parseInt(tok); } public boolean isOperator() { return !isInt; } public char operator() { return tok.charAt(0); } }