如何在java中计算表达式?

时间:2022-06-04 21:20:07

How to calculate user given Expression in java.

如何在java中计算用户给定的表达式。

E:g, if the given exp is 3*4+(5*6) how to calculate this. can anyone help me out.

E:g,如果给定的exp是3*4+(5*6)如何计算这个。谁能帮帮我吗?

4 个解决方案

#1


4  

I found this code after a quick google:

我在简单的谷歌之后找到了这个代码:

import java.util.Stack;

/**
 * Class to evaluate infix and postfix expressions.
 * 
 * @author Paul E. Davis (feedback@willcode4beer.com)
 */
public class InfixPostfixEvaluator {

        /**
         * Operators in reverse order of precedence.
         */
        private static final String operators = "-+/*";
        private static final String operands = "0123456789";

        public int evalInfix(String infix) {
                return evaluatePostfix(convert2Postfix(infix));
        }

        public String convert2Postfix(String infixExpr) {
                char[] chars = infixExpr.toCharArray();
                Stack<Character> stack = new Stack<Character>();
                StringBuilder out = new StringBuilder(infixExpr.length());

                for (char c : chars) {
                        if (isOperator(c)) {
                                while (!stack.isEmpty() && stack.peek() != '(') {
                                        if (operatorGreaterOrEqual(stack.peek(), c)) {
                                                out.append(stack.pop());
                                        } else {
                                                break;
                                        }
                                }
                                stack.push(c);
                        } else if (c == '(') {
                                stack.push(c);
                        } else if (c == ')') {
                                while (!stack.isEmpty() && stack.peek() != '(') {
                                        out.append(stack.pop());
                                }
                                if (!stack.isEmpty()) {
                                        stack.pop();
                                }
                        } else if (isOperand(c)) {
                                out.append(c);
                        }
                }
                while (!stack.empty()) {
                        out.append(stack.pop());
                }
                return out.toString();
        }

        public int evaluatePostfix(String postfixExpr) {
                char[] chars = postfixExpr.toCharArray();
                Stack<Integer> stack = new Stack<Integer>();
                for (char c : chars) {
                        if (isOperand(c)) {
                                stack.push(c - '0'); // convert char to int val
                        } else if (isOperator(c)) {
                                int op1 = stack.pop();
                                int op2 = stack.pop();
                                int result;
                                switch (c) {
                                case '*':
                                        result = op1 * op2;
                                        stack.push(result);
                                        break;
                                case '/':
                                        result = op2 / op1;
                                        stack.push(result);
                                        break;
                                case '+':
                                        result = op1 + op2;
                                        stack.push(result);
                                        break;
                                case '-':
                                        result = op2 - op1;
                                        stack.push(result);
                                        break;
                                }
                        }
                }
                return stack.pop();
        }
        private int getPrecedence(char operator) {
                int ret = 0;
                if (operator == '-' || operator == '+') {
                        ret = 1;
                } else if (operator == '*' || operator == '/') {
                        ret = 2;
                }
                return ret;
        }
        private boolean operatorGreaterOrEqual(char op1, char op2) {
                return getPrecedence(op1) >= getPrecedence(op2);
        }

        private boolean isOperator(char val) {
                return operators.indexOf(val) >= 0;
        }

        private boolean isOperand(char val) {
                return operands.indexOf(val) >= 0;
        }

}

From: http://willcode4beer.com/design.jsp?set=evalInfix

来自:http://willcode4beer.com/design.jsp?set=evalInfix

#2


2  

Take a look at Java Expression evaluator: http://java.net/projects/eval/pages/Home

看看Java表达式求值器:http://java.net/projects/eval/pages/Home

#3


2  

Java does this already. No need to download anything.

Java这了。不需要下载任何东西。

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class EvaluationExample {
    public static void main(String[] args) throws Exception{
        System.out.println(new ScriptEngineManager().getEngineByName("JavaScript").eval("3*4+(5*6)"));
    } 
}

(This is not the first SO answer to show how to use scripting in Java. I only added it here in case people looking at this page do not follow the links. Parsing is fun, and valuable to study, but if you just need to evaluate user-supplied expressions, use a script.)

(这不是第一个演示如何在Java中使用脚本的SO答案。我只是在这里添加了它,以防看到这个页面的人不跟随链接。解析很有趣,也很有研究价值,但如果您只需要评估用户提供的表达式,请使用脚本。

UPDATE The OP is looking for a postfix evaluation solution. This has to be done in two steps: first convert the input string into postfix notation, then run the postfix "code" through a (presumably stack-based evaluator). See PaulPRO's answer for this. If you are willing to use JavaCC or another parser generator, you can be much more flexible with the strings you accept, allowing newlines and other whitespace.

更新OP是为了寻找后缀评估解决方案。这需要通过两个步骤完成:首先将输入字符串转换为后缀表示法,然后通过一个(可能是基于堆栈的求值程序)运行后缀“代码”。看看PaulPRO对此的回答。如果您愿意使用JavaCC或其他解析器生成器,您可以更灵活地使用所接受的字符串,允许使用换行符和其他空格。

#4


0  

Here's a spoiler (Mathematical Expression Parse in Java).

这里是一个扰流器(Java中的数学表达式解析)。

#1


4  

I found this code after a quick google:

我在简单的谷歌之后找到了这个代码:

import java.util.Stack;

/**
 * Class to evaluate infix and postfix expressions.
 * 
 * @author Paul E. Davis (feedback@willcode4beer.com)
 */
public class InfixPostfixEvaluator {

        /**
         * Operators in reverse order of precedence.
         */
        private static final String operators = "-+/*";
        private static final String operands = "0123456789";

        public int evalInfix(String infix) {
                return evaluatePostfix(convert2Postfix(infix));
        }

        public String convert2Postfix(String infixExpr) {
                char[] chars = infixExpr.toCharArray();
                Stack<Character> stack = new Stack<Character>();
                StringBuilder out = new StringBuilder(infixExpr.length());

                for (char c : chars) {
                        if (isOperator(c)) {
                                while (!stack.isEmpty() && stack.peek() != '(') {
                                        if (operatorGreaterOrEqual(stack.peek(), c)) {
                                                out.append(stack.pop());
                                        } else {
                                                break;
                                        }
                                }
                                stack.push(c);
                        } else if (c == '(') {
                                stack.push(c);
                        } else if (c == ')') {
                                while (!stack.isEmpty() && stack.peek() != '(') {
                                        out.append(stack.pop());
                                }
                                if (!stack.isEmpty()) {
                                        stack.pop();
                                }
                        } else if (isOperand(c)) {
                                out.append(c);
                        }
                }
                while (!stack.empty()) {
                        out.append(stack.pop());
                }
                return out.toString();
        }

        public int evaluatePostfix(String postfixExpr) {
                char[] chars = postfixExpr.toCharArray();
                Stack<Integer> stack = new Stack<Integer>();
                for (char c : chars) {
                        if (isOperand(c)) {
                                stack.push(c - '0'); // convert char to int val
                        } else if (isOperator(c)) {
                                int op1 = stack.pop();
                                int op2 = stack.pop();
                                int result;
                                switch (c) {
                                case '*':
                                        result = op1 * op2;
                                        stack.push(result);
                                        break;
                                case '/':
                                        result = op2 / op1;
                                        stack.push(result);
                                        break;
                                case '+':
                                        result = op1 + op2;
                                        stack.push(result);
                                        break;
                                case '-':
                                        result = op2 - op1;
                                        stack.push(result);
                                        break;
                                }
                        }
                }
                return stack.pop();
        }
        private int getPrecedence(char operator) {
                int ret = 0;
                if (operator == '-' || operator == '+') {
                        ret = 1;
                } else if (operator == '*' || operator == '/') {
                        ret = 2;
                }
                return ret;
        }
        private boolean operatorGreaterOrEqual(char op1, char op2) {
                return getPrecedence(op1) >= getPrecedence(op2);
        }

        private boolean isOperator(char val) {
                return operators.indexOf(val) >= 0;
        }

        private boolean isOperand(char val) {
                return operands.indexOf(val) >= 0;
        }

}

From: http://willcode4beer.com/design.jsp?set=evalInfix

来自:http://willcode4beer.com/design.jsp?set=evalInfix

#2


2  

Take a look at Java Expression evaluator: http://java.net/projects/eval/pages/Home

看看Java表达式求值器:http://java.net/projects/eval/pages/Home

#3


2  

Java does this already. No need to download anything.

Java这了。不需要下载任何东西。

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class EvaluationExample {
    public static void main(String[] args) throws Exception{
        System.out.println(new ScriptEngineManager().getEngineByName("JavaScript").eval("3*4+(5*6)"));
    } 
}

(This is not the first SO answer to show how to use scripting in Java. I only added it here in case people looking at this page do not follow the links. Parsing is fun, and valuable to study, but if you just need to evaluate user-supplied expressions, use a script.)

(这不是第一个演示如何在Java中使用脚本的SO答案。我只是在这里添加了它,以防看到这个页面的人不跟随链接。解析很有趣,也很有研究价值,但如果您只需要评估用户提供的表达式,请使用脚本。

UPDATE The OP is looking for a postfix evaluation solution. This has to be done in two steps: first convert the input string into postfix notation, then run the postfix "code" through a (presumably stack-based evaluator). See PaulPRO's answer for this. If you are willing to use JavaCC or another parser generator, you can be much more flexible with the strings you accept, allowing newlines and other whitespace.

更新OP是为了寻找后缀评估解决方案。这需要通过两个步骤完成:首先将输入字符串转换为后缀表示法,然后通过一个(可能是基于堆栈的求值程序)运行后缀“代码”。看看PaulPRO对此的回答。如果您愿意使用JavaCC或其他解析器生成器,您可以更灵活地使用所接受的字符串,允许使用换行符和其他空格。

#4


0  

Here's a spoiler (Mathematical Expression Parse in Java).

这里是一个扰流器(Java中的数学表达式解析)。