添加和减去BODMAS系统

时间:2013-01-25 07:36:01

标签: java math arraylist

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

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

此致

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

你这样做是错的。你需要使用至少一个递归下降表达式解析器,或Dijkstra的分流码算法,甚至可能是一个解析器生成器,如果它将成长为某种语言。您可以通过网络搜索找到所有这些内容。