1 / 10

CS 220 Fall 2013

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);

Download Presentation

CS 220 Fall 2013

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 220 Fall 2013 Postfix and Infix Expressions

  2. ExpEvalGUI

  3. 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"; }

  4. 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); }

  5. MyScanner public class MyScanner { String exp; int position; public MyScanner(String e) { exp = e; position = 0; }

  6. 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); }

  7. MyScanner else if ((new String("+-*/^%()")).indexOf(ch) != -1) { position++; return new Token(""+ch, false); } else return null; } }

  8. Token public class Token { String tok; boolean isInt; public Token(String e, boolean b) { tok = e; isInt = b; } public boolean isInt() { return isInt; }

  9. Token public int intVal() { return Integer.parseInt(tok); } public boolean isOperator() { return !isInt; } public char operator() { return tok.charAt(0); } }

More Related