我一直在构建一个简单的公式计算器,并且被加法和减法困住了。如您所知,在计算方程式时,您遵循优先级的算术规则,即括号,顺序:幂函数,除法,乘法,加法和减法。问题是加法和减法的优先级相同,因此您可以从左到右阅读它。到目前为止,这是我的代码:
{
ArrayList<String> equation = java.util.Arrays.asList({"2","-","2","+","5"});
while(equation.contains("+")){
addMe(equation);
}
while(equation.contains("-")){
minusMe(equation);
}
}
public static void addMe(ArrayList<String> numberList){
for (int i = 0, n = numberList.size(); i < n; i++) {
String value = (String) numberList.get(i);
if(value.equals("+")){
String wordBefore = (String) numberList.get(i-1);
String wordAfter = (String) numberList.get(i+1);
System.out.println("This is the word before " + wordBefore);
System.out.println("This is the word after " + wordAfter);
double doubleFromBefore = Double.parseDouble(wordBefore);
double doubleFromAfter = Double.parseDouble(wordAfter);
double answer = doubleFromBefore + doubleFromAfter;
System.out.println("This is the answer: " + answer);
String stringAnswer = String.valueOf(answer);
String newNum2 = value.replace(value, stringAnswer);
numberList.set(i,newNum2);
numberList.remove(i-1);
numberList.remove(i);
break;
}
}
}
minusMe 方法与 addMe 方法完全一样,只是在相关位置带有“-”。我遇到的问题是一次从左到右读取一个项目,然后执行加法或减法。理想情况下,我认为我需要将我的 2 个 while 循环与迭代器结合起来,以解决问题,但我的尝试没有奏效。关于这是否能解决我的问题的任何想法?如果是这样,请提供修改后的循环。
问候