如何使程序根据数学运算顺序进行计算? (Java)

How to make program to calculate accordingly to Order of operations in math? (Java)

我正在尝试在 Java 中编写一个程序,它接受一个字符串值的输入 像 s = "1+27-63*5/3+2" 和 returns 整数值的计算

下面是我的代码

package numberofcharacters;
import java.util.ArrayList;
public class App {
    public static void main(String[] args) {
        String toCalculate = "123+98-79÷2*5";
        int operator_count = 0;  
        ArrayList<Character> operators = new ArrayList<>();
        for (int i=0; i < toCalculate.length(); i++){
             if (toCalculate.charAt(i) == '+' || toCalculate.charAt(i) == '-' ||
                 toCalculate.charAt(i) == '*' || toCalculate.charAt(i) == '÷' ) {
             operator_count++;  /*Calculating
                                  number of operators in a String toCalculate
                                */
             operators.add(toCalculate.charAt(i)); /* Adding that operator to 
                                                    ArrayList*/
         }
     }
     System.out.println("");
     System.out.println("Return Value :" );

     String[] retval = toCalculate.split("\+|\-|\*|\÷", operator_count + 1);    

    int num1 = Integer.parseInt(retval[0]);
    int num2 = 0;
    int j = 0;
    for (int i = 1; i < retval.length; i++) {

        num2 = Integer.parseInt(retval[i]);
        char operator = operators.get(j);
        if (operator == '+') {
            num1 = num1 + num2;

        }else if(operator == '-'){
            num1 = num1 - num2;
        }else if(operator == '÷'){
            num1 = num1 / num2;
        }else{
            num1 = num1 * num2;
        }
        j++;            
    }
    System.out.println(num1);   // Prints the result value
    }

}

****问题是我需要按照数学中的运算顺序进行计算,比如先乘除,然后再进行加减。 我该如何解决这个问题? ****

我已经使用 String split() 方法在出现运算符“+-/*”的位置分隔字符串。我已经使用字符 ArrayList 在其中添加运算符。 在代码的最后一部分,我在 拆分字符串数组 中循环,并且通过将其解析为 Integer,使用拆分字符串数组的第一个值初始化 int num1。和具有第二个值的 int num2 和使用运算符 arraylist 在它们之间执行计算(无论 arraylist 的该索引处的运算符是什么)。并将结果存储在 int num1 中,反之亦然,直到字符串数组结束。

[P.S] 我尝试使用 Collection.sort 但它按 [*、+、-、/] 的顺序对上述运算符数组列表进行排序。它把除法放在最后,而应该把除法放在乘法符号

之前或之后

如果你想用大致相同的代码结构来完成它,而不是先把它变成类似逆波兰符号的东西,你可以尝试一种以相反的优先顺序处理操作的方法。

因此假设您将 */ 作为最高优先级,并且您将它们视为同等优先级,因此要处理 left-to-right; +- 也一样;那么你会

  1. 首先在 +- 上拆分。
  2. 评估由 +- 分隔的部分,但现在按 left-to-right 顺序处理 */
  3. 将您的 +- 应用到这些评估部分。

因此,如果您的表达式是 3*4+5-6/2,那么您的代码将首先拆分为

3*4  +  5  -  6/2

现在评价这些sub-expressions

12  +  5  -  3

现在处理left-to-right以评估最终答案

14

更笼统地说,您需要通过表达式的次数取决于您拥有的优先级数;并且您需要从最低到最高处理优先级。拆分表达式;递归评估 sub-expressions 仅考虑下一个优先级别及更高级别;结合起来得到最终答案。

这将是一个不错的小 Java 8 流练习!