Created
February 4, 2016 20:00
-
-
Save Ivoah/6f8c676ba4c489bfd293 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
public class Evaluator { | |
public class ParseException extends Exception { | |
public ParseException () { | |
super("Error parsing string"); | |
} | |
public ParseException(String msg) { | |
super(msg); | |
} | |
} | |
public int eval(String expr) throws EmptyStackException, ParseException { | |
return 0; | |
} | |
} |
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
public class RPN extends Evaluator { | |
Stack<Integer> stack = null; | |
public int eval(String expr) throws EmptyStackException, ParseException { | |
stack = new Stack<Integer>(); | |
for (int i = 0; i < expr.length(); i++) { | |
char c = expr.charAt(i); | |
if (c >= '0' && c <= '9') { | |
int num = c - '0'; | |
i++; | |
while ( i < expr.length() && (expr.charAt(i) >= '0' && expr.charAt(i) <= '9')) { | |
num = num*10 + expr.charAt(i) - '0'; | |
i++; | |
} | |
i--; | |
stack.push(num); | |
} else if (c == ' ') { | |
// Ignore it! | |
} else if (c == '*' || c == '/' || c == '%' || c == '+' || c == '-') { | |
apply(c); | |
} else { | |
throw ParseException("Unknown symbol: " + c); | |
} | |
} | |
return stack.pop(); | |
} | |
private void apply(char op) throws EmptyStackException { | |
int v2 = stack.pop(); | |
int v1 = stack.pop(); | |
int ans = 0; | |
switch (op) { | |
case '*': | |
ans = v1 * v2; | |
break; | |
case '/': | |
ans = v1 / v2; | |
break; | |
case '%': | |
ans = v1 % v2; | |
break; | |
case '+': | |
ans = v1 + v2; | |
break; | |
case '-': | |
ans = v1 - v2; | |
break; | |
} | |
stack.push(ans); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment