You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将包含多操作数的数学表达式字符串转换为int类型?

Evaluating Multi-Part Mathematical Expressions in Java

Hey there! Let's tackle this problem step by step. I get that you've nailed evaluating simple two-operand, single-operator expressions, but multi-part expressions (like 3 + 4 * 2 or 10 - 2 + 5) are giving you trouble. Here are a couple of practical approaches you can implement in your math quiz program:

1. Manual Parsing (Great for Learning the Logic)

If you want to understand how expression evaluation works under the hood, building a parser that handles operator precedence (multiplication/division before addition/subtraction) manually is a solid learning exercise. Here's a breakdown of the logic and a sample implementation:

Step-by-Step Logic:

  • Split the expression into a list of numbers and a list of operators (e.g., 3+5*2 becomes numbers [3,5,2] and operators [+, *])
  • First process all multiplication and division operations: iterate through the operator list, compute the result whenever you hit * or /, update the numbers list, and remove the used operator
  • Then process the remaining addition and subtraction operations with the updated numbers list
  • The final remaining number is the evaluated result

Sample Code:

import java.util.ArrayList;
import java.util.List;

public class ExpressionEvaluator {
    public static int evaluate(String expression) throws IllegalArgumentException {
        // Split into numbers and operators
        List<Integer> numbers = new ArrayList<>();
        List<Character> operators = new ArrayList<>();
        StringBuilder numBuilder = new StringBuilder();

        for (char c : expression.toCharArray()) {
            if (Character.isDigit(c)) {
                numBuilder.append(c);
            } else if (c == '+' || c == '-' || c == '*' || c == '/') {
                numbers.add(Integer.parseInt(numBuilder.toString()));
                numBuilder.setLength(0);
                operators.add(c);
            } else {
                throw new IllegalArgumentException("Invalid character in expression: " + c);
            }
        }
        // Add the last number
        numbers.add(Integer.parseInt(numBuilder.toString()));

        // Process multiplication and division first
        int i = 0;
        while (i < operators.size()) {
            char op = operators.get(i);
            if (op == '*' || op == '/') {
                int num1 = numbers.get(i);
                int num2 = numbers.get(i + 1);
                int result;
                if (op == '*') {
                    result = num1 * num2;
                } else {
                    if (num2 == 0) {
                        throw new ArithmeticException("Division by zero");
                    }
                    result = num1 / num2;
                }
                // Update lists
                numbers.set(i, result);
                numbers.remove(i + 1);
                operators.remove(i);
            } else {
                i++;
            }
        }

        // Process addition and subtraction
        int finalResult = numbers.get(0);
        for (int j = 0; j < operators.size(); j++) {
            char op = operators.get(j);
            int num = numbers.get(j + 1);
            if (op == '+') {
                finalResult += num;
            } else {
                finalResult -= num;
            }
        }

        return finalResult;
    }

    // Test it out
    public static void main(String[] args) {
        System.out.println(evaluate("3+5*2")); // Should output 13
        System.out.println(evaluate("10-2+5")); // Should output 13
    }
}

2. Use Java's Built-in ScriptEngine (Quick and Easy)

If you don't want to reinvent the wheel, Java has a built-in script engine that can evaluate JavaScript expressions. This is a fast way to get up and running without writing tons of parsing logic:

Sample Code:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptEngineEvaluator {
    public static int evaluate(String expression) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        // Evaluate the expression and cast to Integer
        return ((Number) engine.eval(expression)).intValue();
    }

    public static void main(String[] args) throws ScriptException {
        System.out.println(evaluate("3+5*2")); // Outputs 13
        System.out.println(evaluate("8/2+3")); // Outputs 7
    }
}

Quick Notes:

  • Don't forget to handle exceptions like ScriptException (for invalid expressions) and ArithmeticException (for division by zero) in your main program when using these methods.
  • If you're building this for a quiz, add input validation to prevent malformed expressions from crashing your program.

内容的提问来源于stack exchange,提问作者Julio Delgado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:28:07