Using Static Initialisation

master
Hammy 4 years ago
parent 9b6674e157
commit 1a99a6dca4

@ -4,6 +4,25 @@ public class MathEquation {
private char opCode;
private double result;
private static int numOfCalculations;
private static double sumOfResults;
// Empty constructor to allow us to use MathEquation without needing to pass in anything
public MathEquation() {}
// This only exists as a demo for chaining constructors
public MathEquation(char opCode) {
this.opCode = opCode;
}
// Demonstrating how chaining constructors works
public MathEquation(char opCode, double leftVal, double rightVal) {
this(opCode);
this.leftVal = leftVal;
this.rightVal = rightVal;
}
// Method to execute the calculations
void execute() {
switch (this.opCode) {
case 'a':
@ -23,6 +42,12 @@ public class MathEquation {
this.result = 0.0d;
break;
}
numOfCalculations++;
sumOfResults += result;
}
public static double getAverageResult() {
return sumOfResults / numOfCalculations;
}
public MathEquation(double leftVal, double rightVal, char opCode, double result) {

@ -1,5 +1,3 @@
import java.util.ArrayList;
public class NewCalcEngine {
public static void main(String[] args) {
@ -9,24 +7,16 @@ public class NewCalcEngine {
static void performCalculations() {
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');
mathEquation[0] = new MathEquation('d', 100.0d, 50.0d);
mathEquation[1] = new MathEquation('a', 25.0d, 92.0d);
mathEquation[2] = new MathEquation('s', 225.0d, 17.0d);
mathEquation[3] = new MathEquation('m', 11.0d, 3.0d);
for (MathEquation equation: mathEquation) {
for (MathEquation equation : mathEquation) {
equation.execute();
System.out.println("Result = " + equation.result);
System.out.println("Result = " + equation.getResult());
}
}
static MathEquation create(double leftVal, double rightVal, char opCode) {
MathEquation mathEquation = new MathEquation();
mathEquation.leftVal = leftVal;
mathEquation.rightVal = rightVal;
mathEquation.opCode = opCode;
return mathEquation;
System.out.println("Average Result = " + MathEquation.getAverageResult());
}
}
Loading…
Cancel
Save