java 如何使程序根据数学运算的顺序进行相应的计算?(爪哇)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34904895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:31:47  来源:igfitidea点击:

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

javastringfor-looparraylistcalculator

提问by Ahmed Adnan

I am trying to write a program in Java which takes input a String value like s = "1+27-63*5/3+2"and returns the calculation in integer value

我正在尝试用 Java 编写一个程序,它输入一个字符串值,如s = "1+27-63*5/3+2"并以整数值返回计算

Here below is my code

下面是我的代码

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
    }

}

****The problem is I need to perform calculation according to Order of operations in Math like Multiplication and division first , than addition and subtraction. How can I resolve this? ****

****问题是我需要根据数学中的运算顺序执行计算,例如乘法和除法,而不是加法和减法。我该如何解决这个问题?****

I have used String split() method to seperate the String wherever the operators "+-/*" occurs. I have used character ArrayList to add operators in it. Than at the last portion of code I am looping in that splitted array of Stringsand I've initialize int num1 with the first value of splitted array of strings by parsing it to Integer. and int num2 with the second value and the using operators arraylist to perform calculation between them (whatever the operator at that index of arraylist). and storing the result in int num1 and doing vice versa until the end of the string array.

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

[P.S] I tried to use Collection.sort but it sorts the above arraylist of operators in that order [*, +, -, /]. It puts division at the end while it should put division after or before multiplication symbol

[PS] 我尝试使用 Collection.sort,但它按照 [*、+、-、/] 的顺序对上面的运算符数组列表进行排序。将除法放在最后,而应将除法放在乘法符号之后或之前

回答by chiastic-security

If you want to do it with roughly the same structure of code, and not turn it into something like reverse Polish notation first, you could try an approach that deals with the operations in reverse priority order.

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

So assuming that you have *and /as highest precedence, and you're treating them as equal precedence and therefore to be dealt with left-to-right; and the same for +and -; then you would

因此,假设您拥有*/作为最高优先级,并且您将它们视为同等优先级,因此要从左到右进行处理;与同为+-; 那么你会

  1. Split first on +and -.
  2. Evaluate the parts that are separated by +and -, but now processing *and /in left-to-right order.
  3. Apply your +and -to these evaluated parts.
  1. 首先在+和上拆分-
  2. 评估由+和分隔的部分-,但现在按从左到右的顺序处理*/
  3. 将您的+-应用于这些评估的部分。

So if your expression is 3*4+5-6/2then your code would split first into

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

3*4  +  5  -  6/2

Now evaluate these sub-expressions

现在评估这些子表达式

12  +  5  -  3

Now process left-to-right to evaluate the final answer

现在从左到右处理以评估最终答案

14

In more general terms, the number of passes you'll need through your expression is determined by the number of precedence levels you have; and you need to process the precedence levels from lowest to highest. Split expression up; recursively evaluate sub-expressions just considering next precedence level and upwards; combine to get final answer.

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

This would be a nice little Java 8 streams exercise!

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