import java.math.BigDecimal; public class CalculateNum { public BigDecimal cal(String str) { if (str == null) { return null; } String fuhao = ""; int index = 0; str = str.replaceAll("--", "+"); // 等价替换; str = str.replaceAll(" ", ""); // 去掉空格 fuhao = "("; index = str.lastIndexOf(fuhao); if (index >= 0) { int rightIndex = str.indexOf(")", index); String left = str.substring(0, index); String right = ""; if (rightIndex + 1 < str.length()) { right = str.substring(rightIndex + 1); } BigDecimal middle = cal(str.substring(index + 1, rightIndex)); return cal(left + middle + right); } fuhao = "+"; index = str.lastIndexOf(fuhao); if (index > 0) { BigDecimal left = cal(str.substring(0, index)); BigDecimal right = cal(str.substring(index + 1)); return left.add(right); } fuhao = "-"; index = str.lastIndexOf(fuhao); if (index == 0) { // 负数处理 BigDecimal result = cal(str.substring(index + 1)); if (result.compareTo(new BigDecimal("0")) == -1) { // 小于0 return result.abs(); // 绝对值 } else { return result.negate(); // 相反数 } } else if (index > 0) { BigDecimal left = cal(str.substring(0, index)); BigDecimal right = cal(str.substring(index + 1)); return left.subtract(right); } fuhao = "*"; index = str.lastIndexOf(fuhao); if (index > 0) { BigDecimal left = cal(str.substring(0, index)); BigDecimal right = cal(str.substring(index + 1)); return left.multiply(right); } fuhao = "/"; index = str.lastIndexOf(fuhao); if (index > 0) { BigDecimal left = cal(str.substring(0, index)); BigDecimal right = cal(str.substring(index + 1)); return left.divide(right); } return new BigDecimal(str); } }
JAVA乘除在一起先算谁_java实现四则运算,难点主要在理解加减乘除优先级以及使用递归...
最新推荐文章于 2021-08-09 00:00:18 发布