import java.util.*; import java.util.regex.Pattern; public class EvaluateDemo { public static final Pattern CHARACTER = Pattern.compile("\\S.*?"); public static final Pattern INT = Pattern.compile("[+-]?\\d+.*?"); public static final Pattern UNSIGNED_DOUBLE = Pattern.compile("((\\d+\\.?\\d*)|(\\.\\d+))([Ee][-+]?\\d+)?.*?"); public static final Pattern UNSIGNED_INT = Pattern.compile("\\d+.*?"); public static void main(String[] args) { String expr; Scanner input = new Scanner(System.in); System.out.print("Enter an expression: "); expr = input.nextLine(); double x = evaluate(expr); System.out.println("Answer = " + x); } public static double evaluate(String expression) { Stack numbers = new Stack(); Stack operations = new Stack(); Scanner input = new Scanner(expression); String next; while (input.hasNext()) { if (input.hasNext(UNSIGNED_DOUBLE)) { next = input.findInLine(UNSIGNED_DOUBLE); numbers.push(new Double(next)); } else { next = input.findInLine(CHARACTER); switch (next.charAt(0)) { case '+': case '-': case '*': case '/': operations.push(next.charAt(0)); break; case ')': evaluateStackTops(numbers, operations); break; case '(': break; default: throw new IllegalArgumentException("Illegal character"); } } } if (numbers.size() != 1 || !operations.isEmpty()) { throw new IllegalArgumentException("Illegal input expression"); } return numbers.pop(); } public static void evaluateStackTops(Stack numbers, Stack operations) { double operand1, operand2; if ((numbers.size() < 2) || (operations.isEmpty())) throw new IllegalArgumentException("Illegal expression"); operand2 = numbers.pop(); operand1 = numbers.pop(); switch (operations.pop()) { case '+': numbers.push(operand1 + operand2); break; case '-': numbers.push(operand1 - operand2); break; case '*': numbers.push(operand1 * operand2); break; case '/': numbers.push(operand1 / operand2); break; default: throw new IllegalArgumentException("Illegal operation"); } } }