import java.util.Vector; public class Calculator { static boolean isDelim(char c) { return c == ' '; } static boolean isOperator(char c) { return c == '+' || c == '-' || c == '/' || c == '*' || c == '%' || c == '^'; } static int priority(char op) { switch (op) { case '+': case '-': return 1; case '*': case '/': case '%': return 2; case '^': return 3; default: return -1; } } static float removeLast(Vector v) { float r = 0; try { r = ((Float) v.lastElement()).floatValue(); } catch (Exception ee) {} v.removeElementAt(v.size() - 1); return r; } static char cremoveLast(Vector v) { char r = 0; try { r = ((Character) v.lastElement()).charValue(); } catch (Exception ee) {} v.removeElementAt(v.size() - 1); return r; } static float powTaylor(float a, float b) { boolean gt1 = (Math.sqrt((a - 1) * (a - 1)) > 1); int oc = -1, iter = 30; double p = a, x, x2, sumX, sumY; if ((b - Math.floor(b)) == 0) { for (int i = 1; i < b; i++) p *= a; return (float) p; } x = (gt1) ? (a / (a - 1)) : (a - 1); sumX = (gt1) ? (1 / x) : x; for (int i = 2; i < iter; i++) { p = x; for (int j = 1; j < i; j++) p *= x; double xTemp = (gt1) ? (1 / (i * p)) : (p / i); sumX = (gt1) ? (sumX + xTemp) : (sumX + (xTemp * oc)); oc *= -1; } x2 = b * sumX; sumY = 1 + x2; for (int i = 2; i <= iter; i++) { p = x2; for (int j = 1; j < i; j++) p *= x2; int yTemp = 2; for (int j = i; j > 2; j--) yTemp *= j; sumY += p / yTemp; } return (float) sumY; } static void processOperator(Vector st, char op) { float r = removeLast(st); float l = removeLast(st); switch (op) { case '+': st.addElement(new Float(l + r)); break; case '-': st.addElement(new Float(l - r)); break; case '*': st.addElement(new Float(l * r)); break; case '/': st.addElement(new Float(l / r)); break; case '%': st.addElement(new Float(l % r)); break; case '^': st.addElement(new Float(powTaylor(l, r))); break; } } public static float eval(String s) { Vector st = new Vector(); Vector op = new Vector(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (isDelim(c)) { continue; } if (c == '(') { op.addElement(new Character('(')); } else if (c == ')') { while (((Character) op.elementAt(op.size() - 1)).charValue() != '(') { processOperator(st, cremoveLast(op)); } removeLast(op); } else if (isOperator(c)) { while (!op.isEmpty() && priority(((Character) op.elementAt(op.size() - 1)).charValue()) >= priority(c)) { processOperator(st, cremoveLast(op)); } op.addElement(new Character(c)); } else { String operand = new String(); while (i < s.length() && Character.isDigit(s.charAt(i))) { operand += s.charAt(i++); } --i; try { st.addElement(new Float(Float.parseFloat(operand))); } catch (Exception ee) {} } } while (!op.isEmpty()) { processOperator(st, cremoveLast(op)); } return ((Float) st.elementAt(0)).floatValue(); } }