Refactoring Code To Use OOP

master
sgoudham 4 years ago
parent bd25c0e5d6
commit 9b6674e157
No known key found for this signature in database
GPG Key ID: EF51A29A50FB754C

@ -0,0 +1,68 @@
public class MathEquation {
private double leftVal;
private double rightVal;
private char opCode;
private double result;
void execute() {
switch (this.opCode) {
case 'a':
this.result = this.leftVal + this.rightVal;
break;
case 's':
this.result = this.leftVal - this.rightVal;
break;
case 'm':
this.result = this.leftVal * this.rightVal;
break;
case 'd':
this.result = this.rightVal != 0 ? this.leftVal / this.rightVal : 0.0d;
break;
default:
System.out.println("Invalid opCode: " + this.opCode);
this.result = 0.0d;
break;
}
}
public MathEquation(double leftVal, double rightVal, char opCode, double result) {
this.leftVal = leftVal;
this.rightVal = rightVal;
this.opCode = opCode;
this.result = result;
}
// Setters
public double getLeftVal() {
return leftVal;
}
public void setLeftVal(double leftVal) {
this.leftVal = leftVal;
}
public double getRightVal() {
return rightVal;
}
public void setRightVal(double rightVal) {
this.rightVal = rightVal;
}
public char getOpCode() {
return opCode;
}
public void setOpCode(char opCode) {
this.opCode = opCode;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
}

@ -1,3 +1,5 @@
import java.util.ArrayList;
public class NewCalcEngine {
public static void main(String[] args) {
@ -5,39 +7,26 @@ public class NewCalcEngine {
}
static void performCalculations() {
double[] leftVals = {100.0d, 25.0d, 225.0d, 11.0d};
double[] rightVals = {50.0d, 92.0d, 17.0d, 3.0d};
char[] opCodes = {'d', 'a', 's', 'm'};
double[] results = new double[opCodes.length];
for (int i = 0; i < opCodes.length; i++) {
results[i] = execute(opCodes[i], leftVals[i], rightVals[i]);
}
for (double currentResult : results)
System.out.println("result = " + currentResult);
MathEquation[] mathEquation = new MathEquation[4];
mathEquation[0] = create(100.0d, 50.0d, 'd');
mathEquation[1] = create(25.0d, 92.0d, 'a');
mathEquation[2] = create(225.0d, 17.0d, 's');
mathEquation[3] = create(11.0d, 3.0d, 'm');
for (MathEquation equation: mathEquation) {
equation.execute();
System.out.println("Result = " + equation.result);
}
}
static double execute(char opCode, double leftVal, double rightVal) {
double result;
switch (opCode) {
case 'a':
result = leftVal + rightVal;
break;
case 's':
result = leftVal - rightVal;
break;
case 'm':
result = leftVal * rightVal;
break;
case 'd':
result = rightVal != 0 ? leftVal / rightVal : 0.0d;
break;
default:
System.out.println("Invalid opCode: " + opCode);
result = 0.0d;
break;
}
return result;
static MathEquation create(double leftVal, double rightVal, char opCode) {
MathEquation mathEquation = new MathEquation();
mathEquation.leftVal = leftVal;
mathEquation.rightVal = rightVal;
mathEquation.opCode = opCode;
return mathEquation;
}
}
Loading…
Cancel
Save