Skip to content

Instantly share code, notes, and snippets.

@Ivoah
Created February 4, 2016 20:00
Show Gist options
  • Save Ivoah/6f8c676ba4c489bfd293 to your computer and use it in GitHub Desktop.
Save Ivoah/6f8c676ba4c489bfd293 to your computer and use it in GitHub Desktop.
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;
}
}
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