如何将包含多操作数的数学表达式字符串转换为int类型?
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*2becomes 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) andArithmeticException(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

