在 Java 7 中,您可以避免使用 String 上的 switch 语句编写 if-else 链。
您还应该研究浮点运算。它并不总是表现得像人们预期的那样。
public class SentiEvaluator {
public boolean evaluate(String sentiOp, String sentiScore, double otherValue) {
if (sentiOp == null) {
throw new IllegalArgumentException("Operator must be specified.");
}
if (sentiScore == null) {
throw new IllegalArgumentException("Score must be specified.");
}
double score = Double.parseDouble(sentiScore);
return evaluateJava7(score, sentiOp, otherValue);
}
private boolean evaluateJava7(double leftOp, String operator, double rightOp) {
switch (operator) {
case "=": return leftOp == rightOp;
case ">": return leftOp > rightOp;
case ">=": return leftOp >= rightOp;
case "<": return leftOp < rightOp;
case "<=": return leftOp <= rightOp;
default: throw new IllegalArgumentException("Unknown operator " + operator);
}
}
}