2

我一直在构建一个简单的公式计算器,并且被加法和减法困住了。如您所知,在计算方程式时,您遵循优先级的算术规则,即括号,顺序:幂函数,除法,乘法,加法和减法。问题是加法和减法的优先级相同,因此您可以从左到右阅读它。到目前为止,这是我的代码:

{
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 循环与迭代器结合起来,以解决问题,但我的尝试没有奏效。关于这是否能解决我的问题的任何想法?如果是这样,请提供修改后的循环。

问候

4

2 回答 2

3

看看这个

java.uti.ArrayList<String> equation = java.util.Arrays.asList({"2","-","2","+","5"});
java.util.Iterator<String> equIterator = equation.iterator();
int result = 0;
int multiplier = 1;
while(equIterator.hasNext()){
     String operandOrOperator = equIterator.next();
     if(operandOrOperator.equals("+")){
          multiplier=1;
     }else if(operandOrOperator.equals("-")){
          multiplier=-1;
     }else if(operandOrOperator.equals("*")){
          result*=Integer.parseInt(equIterator.next()); // Assuming that next element will be there always after operator.
     }else{
          result+=(multiplier * Integer.parseInt(operandOrOperator));
     }
}
System.out.println("Final result : " + result);
于 2013-01-25T07:56:19.693 回答
0

你做这一切都是错的。您至少需要使用递归下降表达式解析器,或 Dijkstra 的 shunting-yard 算法,如果要发展成某种语言,甚至可能需要使用解析器生成器。您将通过网络搜索找到所有这些内容。

于 2013-01-26T23:39:51.827 回答