2021SC@SDUSC
这篇研究ScienceCalculator类中基于BaseCalculator类实现的科学计算
首先是对输入的数学表达式进行预处理,包括去掉里面的空格,将e、π替换为数学中的e和π
math = math.replace(" ", "");
math = math.replace("π", String.valueOf(Math.PI));
math = math.replace("e", String.valueOf(Math.exp(1)));
接下来是对式子中的指数进行运算,将带有指数运算的部分使用pow计算后把原来的式子替换
//(2)计算指数(pow)运算并替换,包括(x)^(y)
while (math.contains("^")) {
//1.中间寻找的点
int midIndex = math.lastIndexOf("^");
//2.获取左边参数
double leftNum; //左边的数
String leftStr; //左边math字符串
int leftIndex = midIndex - 1;
if (math.charAt(leftIndex) == ')') { //1.左边是一个表达式,即左边用括号括起来
int i = leftIndex - 1;
while (math.charAt(i) != '(') {
i--;
}
String subLeftMath = math.substring(i + 1, leftIndex);
leftNum = baseCalculator.cal(subLeftMath);
if (leftNum == Double.MAX_VALUE) //每次计算要判断是否出现 math error
return Double.MAX_VALUE;
leftStr = "(" + subLeftMath + ")";
} else { //2.左边是一个数
//注意:判定index范围一定要在左边,否则可能出现IndexOutOfRange异常
while (leftIndex >= 0 && !isOper(math.charAt(leftIndex))) {
leftIndex--;
}
leftStr = math.substring(leftIndex + 1, midIndex);
leftNum = Double.parseDouble(leftStr);
}
//3.获取右边参数
double rightNum;
String rightStr;
int rightIndex = midIndex + 1;
if (math.charAt(rightIndex) == '(') {
int i = rightIndex + 1;
while (math.charAt(i) != ')') {
i++;
}
String subRightMath = math.substring(rightIndex + 1, i);
rightNum = baseCalculator.cal(subRightMath);
if (rightNum == Double.MAX_VAL