Advertisement
Guest User

oapIHW;oeihg;oihnb;oinaioIshofrdjoawl

a guest
Nov 21st, 2014
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. // represents the operation to be performed on two variables
  2. // @author Chris Tsuei
  3.  
  4. public class ArithmeticOperation extends Expression{
  5.  
  6. /*operation is the action(+, -, *, /, %) to be done
  7. * fistVariable and SecondVariable are the variables the operation is to be applied to
  8. * firstValue and secondValue are the values of the firstVariable and secondVariable respectively
  9. */
  10. public Operator operation;
  11. public Expression firstVariable;
  12. public Expression secondVariable;
  13. public int firstValue;
  14. public int secondValue;
  15.  
  16. //enum class of the ArithmeticOperation class
  17. private static enum Operator{
  18. //the user can either add, subtract, multiply, divide or moduolo
  19. Add, Sub, Mult, Div, Rem;}
  20.  
  21. public ArithmeticOperation(Operator operator, Expression variable, Expression variable2) {
  22. this.operation = operator;
  23. this.firstVariable = variable;
  24. this.secondVariable = variable2;
  25. }
  26.  
  27. /*gets the value of the operation
  28. * @Override
  29. * @param state the hashtable holding all of the variables
  30. * @return the result of the operation
  31. */
  32. public int value(State state) {
  33. this.firstValue = firstVariable.value(state);
  34. this.secondValue = secondVariable.value(state);
  35.  
  36. if(operation.equals("Add")) {
  37. return firstValue + secondValue;
  38. }
  39. else if(operation.equals("Sub")) {
  40. return firstValue - secondValue;
  41. }
  42. else if(operation.equals("Mult")) {
  43. return firstValue * secondValue;
  44. }
  45. else if(operation.equals("Div")) {
  46. return firstValue / secondValue;
  47. }
  48. else {
  49. return firstValue % secondValue;
  50. }
  51. }
  52.  
  53. /* @Override overides the toString() method
  54. * @return returns the string value of the operation
  55. */
  56. public String toString() {
  57. char op;
  58. if(operation.equals("Add")) {
  59. op = '+';
  60. }
  61. else if(operation.equals("Sub")) {
  62. op = '-';
  63. }
  64. else if(operation.equals("Mult")) {
  65. op = '*';
  66. }
  67. else if(operation.equals("Div")) {
  68. op = '/';
  69. }
  70. else {
  71. op = '%';
  72. }
  73. return firstValue + " " + op + " " + secondValue;
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement