Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // represents the operation to be performed on two variables
- // @author Chris Tsuei
- public class ArithmeticOperation extends Expression{
- /*operation is the action(+, -, *, /, %) to be done
- * fistVariable and SecondVariable are the variables the operation is to be applied to
- * firstValue and secondValue are the values of the firstVariable and secondVariable respectively
- */
- public Operator operation;
- public Expression firstVariable;
- public Expression secondVariable;
- public int firstValue;
- public int secondValue;
- //enum class of the ArithmeticOperation class
- private static enum Operator{
- //the user can either add, subtract, multiply, divide or moduolo
- Add, Sub, Mult, Div, Rem;}
- public ArithmeticOperation(Operator operator, Expression variable, Expression variable2) {
- this.operation = operator;
- this.firstVariable = variable;
- this.secondVariable = variable2;
- }
- /*gets the value of the operation
- * @Override
- * @param state the hashtable holding all of the variables
- * @return the result of the operation
- */
- public int value(State state) {
- this.firstValue = firstVariable.value(state);
- this.secondValue = secondVariable.value(state);
- if(operation.equals("Add")) {
- return firstValue + secondValue;
- }
- else if(operation.equals("Sub")) {
- return firstValue - secondValue;
- }
- else if(operation.equals("Mult")) {
- return firstValue * secondValue;
- }
- else if(operation.equals("Div")) {
- return firstValue / secondValue;
- }
- else {
- return firstValue % secondValue;
- }
- }
- /* @Override overides the toString() method
- * @return returns the string value of the operation
- */
- public String toString() {
- char op;
- if(operation.equals("Add")) {
- op = '+';
- }
- else if(operation.equals("Sub")) {
- op = '-';
- }
- else if(operation.equals("Mult")) {
- op = '*';
- }
- else if(operation.equals("Div")) {
- op = '/';
- }
- else {
- op = '%';
- }
- return firstValue + " " + op + " " + secondValue;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement