Using enums to avoid using switch/if
Hi, I want to avoid using if cases or switch in the following piece of
code:
package calculator;
public class Operations {
public double calculateResult() {
double totalVal = Calculator.calculator.prevValue;
double val2 = Double.parseDouble
(Calculator.calculator.displayField.getText());
if (Calculator.calculator.operatorUsed.equals("+")) {
totalVal += val2;
}
if (Calculator.calculator.operatorUsed.equals("-")) {
totalVal -= val2;
}
if (Calculator.calculator.operatorUsed.equals("/")) {
totalVal /= val2;
}
if (Calculator.calculator.operatorUsed.equals("*")) {
totalVal *= val2;
}
if (Calculator.calculator.operatorUsed.equals("=")) {
totalVal = val2;
}
return totalVal;
}
}
I read in a java tutorial that you can use enums to get rid of this :
public enum Operation {
PLUS {
double eval(double x, double y) {
return x + y;
}
},
MINUS {
double eval(double x, double y) {
return x - y;
}
},
TIMES {
double eval(double x, double y) {
return x * y;
}
},
DIVIDE {
double eval(double x, double y) {
return x / y;
}
};
abstract double eval(double x, double y);
}
But here's my problem: In my program I've strings ("+" , "-", "/", "="
etc) instead of enums. I need a mechanism to map string to enum.