Created
February 11, 2014 23:35
-
-
Save rayjcwu/8946667 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // first version | |
| float eval(String str) { | |
| String [] tokens = str.split(" "); | |
| Stack <Float> stack = new Stack<Float>(); | |
| for (String token: tokens) { | |
| if (!isOp(token)) { | |
| } else { | |
| float right = stack.remove(); | |
| float left = stack.remove(); | |
| float t = calculate(token, left, right); | |
| stack.add(t); | |
| } | |
| return stack.peek(); | |
| } | |
| float calculate(String op, float left, float right) { | |
| if (op.equals("+")) { | |
| return left + right; | |
| } else if (op.equals("-")) { | |
| return left - right; | |
| } else if (op.equals("*")) { | |
| return left * right; | |
| } else /*if (op.equals("/"))*/ { | |
| return left / right; | |
| } | |
| } | |
| boolean isOp(String s) { | |
| return (s.eqals("+") || s.equals("-") || s.equals("*") || s.equals("/")); | |
| } | |
| // second version | |
| float eval(String str) { | |
| String [] tokens = str.split(" "); | |
| Stack <Float> stack = new Stack<Float>(); | |
| boolean invalid = false; | |
| for (String token: tokens) { | |
| if (!isOp(token)) { | |
| try { | |
| stack.add(Float.parseInt(token)); | |
| } catch (FormattingException e) { | |
| throw new ArithmeticException(token + " no a valid number"); | |
| } | |
| } else { | |
| if (!stack.empty()) { | |
| float right = stack.remove(); | |
| } else { | |
| invalid = true; | |
| break; | |
| } | |
| if (!stack.empty()) { | |
| float left = stack.remove(); | |
| } else { | |
| invalid = true; | |
| break; | |
| } | |
| float t = calculate(token, left, right); | |
| stack.add(t); | |
| } | |
| } | |
| if (invalid || stack.size() > 1 || stack.size() == 0) { | |
| throw new ArithmeticException(""); | |
| } else { | |
| return stack.peek(); | |
| } | |
| } | |
| float calculate(String op, float left, float right) { | |
| if (op.equals("+")) { | |
| return left + right; | |
| } else if (op.equals("-")) { | |
| return left - right; | |
| } else if (op.equals("*")) { | |
| return left * right; | |
| } else /*if (op.equals("/"))*/ { | |
| if (Math.abs(right) < 1e-9) { // right == 0.0 | |
| throw new ArithmeticException("div by 0"); | |
| } | |
| return left / right; | |
| } | |
| } | |
| boolean isOp(String s) { | |
| return (s.eqals("+") || s.equals("-") || s.equals("*") || s.equals("/")); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment