fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. interface Expression {
  11. public double evaluate();
  12. }
  13.  
  14. static class UnaryExpression implements Expression {
  15. boolean positiveOperator;
  16. Expression operand;
  17.  
  18. public UnaryExpression(Expression operand, boolean positive) {
  19. this.operand = operand;
  20. this.positiveOperator = positive;
  21. }
  22.  
  23. @Override
  24. public double evaluate() {
  25. double value = operand.evaluate();
  26. return positiveOperator ? value : -value;
  27. }
  28. }
  29.  
  30. static class ConstantExpression implements Expression {
  31. double value;
  32.  
  33. public ConstantExpression(double value) {
  34. this.value = value;
  35. }
  36.  
  37. @Override
  38. public double evaluate() { return this.value; }
  39. }
  40.  
  41. static class BinaryExpression implements Expression {
  42. Expression left;
  43. Expression right;
  44. int operator;
  45.  
  46. public static final int PLUS = 0;
  47. public static final int MINUS = 1;
  48. public static final int MULTIPLY = 2;
  49. public static final int DIVIDE = 3;
  50.  
  51. public BinaryExpression(Expression left, Expression right, int operator) {
  52. this.left = left;
  53. this.right = right;
  54. this.operator = operator;
  55. }
  56.  
  57. @Override
  58. public double evaluate() {
  59. double lValue = left.evaluate();
  60. double rValue = right.evaluate();
  61.  
  62. switch(operator) {
  63. case PLUS:
  64. return lValue + rValue;
  65. case MINUS:
  66. return lValue - rValue;
  67. case MULTIPLY:
  68. return lValue * rValue;
  69. case DIVIDE:
  70. return lValue / rValue;
  71. default:
  72. throw new IllegalStateException("Cannot execute operator: " + operator);
  73. }
  74. }
  75. }
  76.  
  77. public static void main (String[] args) throws java.lang.Exception
  78. {
  79. ConstantExpression two = new ConstantExpression(2);
  80. ConstantExpression three = new ConstantExpression(3);
  81. UnaryExpression negTwo = new UnaryExpression(two, false);
  82. BinaryExpression result = new BinaryExpression(negTwo, three, BinaryExpression.PLUS);
  83.  
  84. System.out.println(result.evaluate());
  85. }
  86. }
Success #stdin #stdout 0.09s 320576KB
stdin
Standard input is empty
stdout
1.0