需求: 不同的配件用量数据需要通过不同的参数公式去计算出来,记录一下如何实现这个计算过程!!!
代码写得比较急,比较随意,轻喷。。。。
String regulation = materialParts.getRegulation().trim();
BigDecimal yongLiang = BigDecimal.ZERO;
if (regulation.matches("\\d+")) {
// 如果regulation为纯数字
yongLiang = new BigDecimal(regulation);
} else {
// 如果regulation为参数表达式
String[] splitArr1 = regulation.split("\\+|\\-|\\*|\\/");
List<String> vList = Arrays.asList(splitArr1);
String[] splitArr2 = regulation.split("");
List<String> operationList = new ArrayList<>();
for(String zf: splitArr2) {
if ("+".equals(zf) || "-".equals(zf) || "*".equals(zf) || "/".equals(zf)) {
operationList.add(zf);
}
}
// 如果只是取值,不包含其他运算表达式
if (operationList.isEmpty()) {
yongLiang = mustParamMap.get(vList.get(0));
} else {
int i = 0;
for (String v : vList) {
BigDecimal vBig = null;
if (v.matches("\\d+")) {
vBig = new BigDecimal(v);
} else {
vBig = mustParamMap.get(v);
}
if (i == 0) {
yongLiang = vBig;
i++;
continue;
}
String operationChar = operationList.get(i-1);
if ("+".equals(operationChar)) {
yongLiang = yongLiang.add(vBig);
} else if ("-".equals(operationChar)) {
yongLiang = yongLiang.subtract(vBig);
} else if ("*".equals(operationChar)) {
yongLiang = yongLiang.multiply(vBig);
} else if ("/".equals(operationChar)) {
yongLiang = yongLiang.divide(vBig, 2, BigDecimal.ROUND_HALF_UP);
}
i++;
}
}