Skip to content

Instantly share code, notes, and snippets.

@Robert-Wett
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Robert-Wett/12895f21fd37f475c0ed to your computer and use it in GitHub Desktop.
Save Robert-Wett/12895f21fd37f475c0ed to your computer and use it in GitHub Desktop.
BeginningJavaExpressionParser
import java.util.*;
public class ExpressionParser {
private final static List<String> numList = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
private final static List<String> opList = Arrays.asList("*", "/", "+", "-", "^");
public static void main(String[] args) {
evalExpression("((1024^2)*5)");
}
public static Object evalExpression(String expression) {
if (!isBalancedParens(expression))
return -1; // Err?
Stack<String> stack = new Stack<String>();
for (String token : expression.trim().split("")) {
if (token.equals(" "))
continue;
if (token.equals("(")) {
stack.push(token);
}
else if (numList.contains(token)) {
stack.push(token);
}
else if (opList.contains(token)) {
tokenizeLeadingNumberInStacks(stack);
stack.push(token);
}
else if (token.equals(")")) {
tokenizeLeadingNumberInStacks(stack);
int arg2 = Integer.parseInt(stack.pop());
String operator = stack.pop();
int arg1 = Integer.parseInt(stack.pop());
int results = doMath(arg1, arg2, operator);
stack.pop();
stack.push(Integer.toString(results));
}
}
return (Object) stack.pop();
}
private static void tokenizeLeadingNumberInStacks(Stack<String> stack) {
if (stack.isEmpty() || stack.size() == 1 || !numList.contains(stack.peek()))
return;
Stack<String> reducedStack = new Stack<String>();
while (numList.contains(stack.peek())) {
reducedStack.push(stack.pop());
}
StringBuilder reversedNum = new StringBuilder();
for (int i = 0, startSize = reducedStack.size(); i < startSize; i++) {
reversedNum.append(reducedStack.pop());
}
stack.push(reversedNum.toString());
}
private static int doMath(int arg1, int arg2, String operator) {
switch (operator) {
case "+":
return arg1 + arg2;
case "-":
return arg1 - arg2;
case "*":
return arg1 * arg2;
case "/":
return arg1 / arg2;
case "^":
return (int) Math.pow(arg1, arg2);
default:
return -1;
}
}
public static boolean isBalancedParens(String expression) {
Stack<Object> parens = new Stack<Object>();
for (int i = 0; i < expression.length(); i++) {
if (expression.charAt(i) == '(')
parens.push(new Object());
else if (expression.charAt(i) == ')')
parens.pop();
}
return parens.isEmpty();
}
private enum Ops {
EXPONENT,
DIVIDE,
MULTIPLY,
SUBTRACT,
ADD
}
private static void print(String message) {
System.out.println(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment