public class CalcEngine { public static final int NULL = 0; // (何もしない) public static final int ADD = 1; // 加算 public static final int SUB = 2; // 減算 public static final int MUL = 3; // 乗算 public static final int DIV = 4; // 除算 public static final int MOD = 5; // 剰余 public static final int sqrt = 6; public static final int sin = 7; public static final int cos = 8; public static final int tan = 9; public static final int log = 10; public static final int exp = 11; static final int EMPTY = 0; static final int ONE_NUM = 1; static final int ONE_OP = 2; static final int TWO_NUM = 3; static final int ANSWER = 4; static final int NEXT_NUM = 5; double regA, regB; int op; int state; CalcEngine() { regA = regB = 0.0; op = NULL; state = EMPTY; } public void reset() { regA = regB = 0.0; op = NULL; } public void register(double x) { switch (state) { case EMPTY: regA = x; state = ONE_NUM; break; case ONE_OP: regB = x; state = TWO_NUM; break; case ANSWER: regA = x; state = NEXT_NUM; break; case ONE_NUM: regA = x; break; case TWO_NUM: regB = x; break; case NEXT_NUM: regA = x; break; default: System.err.println("内部エラー"); System.exit(1); } } public double operate(int op) { if (state == TWO_NUM) { calculate(); } this.op = op; state = ONE_OP; return regA; } public double getAnswer() { if (state == ONE_OP) { regB = regA; } calculate(); state = ANSWER; return regA; } void calculate() { switch (this.op) { case ADD: regA = regA + regB; break; case SUB: regA = regA - regB; break; case MUL: regA = regA * regB; break; case DIV: regA = regA / regB; break; case MOD: regA = regA % regB; break; } } double function(int func) { if (state == TWO_NUM) { regB = funcall(func, regB); return regB; } else { regA = funcall(func, regA); return regA; } } double funcall(int func, double x) { switch (func) { case sqrt: return Math.sqrt(x); case sin: return Math.sin(radian(x)); case cos: return Math.cos(radian(x)); case tan: return Math.tan(radian(x)); case log: return Math.log(x); case exp: return Math.exp(x); default: return x; } } public double radian(double deg) { return Math.PI * deg / 180.0; } // test program public static void main(String[] args) { // test program double ans = 0.0; CalcEngine ce = new CalcEngine(); for (int i = 0; i < args.length; i++) { if (args[i].equals("=")) ans = ce.getAnswer(); else if (args[i].equals("+")) ans = ce.operate(ADD); else if (args[i].equals("-")) ans = ce.operate(SUB); else if (args[i].equals("*")) ans = ce.operate(MUL); else if (args[i].equals("/")) ans = ce.operate(DIV); else if (args[i].equals("%")) ans = ce.operate(MOD); else if (args[i].equals("sqrt")) ans = ce.operate(sqrt); else if (args[i].equals("sin")) ans = ce.operate(sin); else if (args[i].equals("cos")) ans = ce.operate(cos); else if (args[i].equals("tan")) ans = ce.operate(tan); else { try { ce.register(Double.parseDouble(args[i])); } catch (NumberFormatException e) { System.err.println(e); } } } System.out.println(ce.getAnswer()); } }