
本文介绍如何安全、规范地将字符串中的数字和运算符提取并计算,重点讲解 Integer.parseInt() 和 Double.parseDouble() 的适用场景、常见陷阱及完整表达式解析实现。
本文介绍如何安全、规范地将字符串中的数字和运算符提取并计算,重点讲解 `integer.parseint()` 和 `double.parsedouble()` 的适用场景、常见陷阱及完整表达式解析实现。
在 Java 中,并不存在 parseInt() 的静态方法直接作用于字符串之外的上下文——正确用法是 Integer.parseInt(String),它仅负责将符合整数格式的字符串(如 "123")转换为 int 值。但需注意:若字符串含空格、符号、小数点或非数字字符(如 "5 + 5" 整体),直接调用会抛出 NumberFormatException。因此,不能对整个表达式字符串调用 parseInt(),而必须先分词(tokenize),再分别解析操作数。
对于类似 "5 + 5" 这样的简单二元表达式,推荐采用基于空格分割的轻量解析策略。以下是一个健壮、可扩展的实现示例:
public class Calculate {
public static void main(String[] args) {
System.out.printf("5 + 5 = %.2f%n", calculate("5 + 5")); // → 10.00
System.out.printf("10 - 3.5 = %.2f%n", calculate("10 - 3.5")); // → 6.50
System.out.printf("4 * 7 = %.2f%n", calculate("4 * 7")); // → 28.00
}
public static double calculate(String input) {
if (input == null || input.trim().isEmpty()) {
throw new IllegalArgumentException("Input cannot be null or empty");
}
String[] tokens = input.trim().split("\s+"); // 按一个或多个空白字符分割
if (tokens.length != 3) {
throw new IllegalArgumentException(
String.format("Invalid format: expected '<num><op><num>', got %d tokens", tokens.length)
);
}
try {
double operand1 = Double.parseDouble(tokens[0]);
double operand2 = Double.parseDouble(tokens[2]);
String operator = tokens[1];
return switch (operator) {
case "+" -> operand1 + operand2;
case "-" -> operand1 - operand2;
case "*", "x" -> operand1 * operand2;
case "/", "÷" -> {
if (operand2 == 0) throw new ArithmeticException("Division by zero");
yield operand1 / operand2;
}
default -> throw new IllegalArgumentException(
"Unsupported operator: '" + operator + "'. Use +, -, *, or /"
);
};
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid number format in expression", e);
}
}
}</num></op></num>
✅ 关键实践建议:
你是 TypeScript 项目架构专家,专注于脚手架搭建生产就绪的 Node.js 和前端应用。生成包含现代工具链(pnpm、Vite、Next.js)、类型
- ✅ 优先使用
Double.parseDouble():支持整数与小数(如"3.14"),避免parseInt()因小数导致崩溃; - ✅ 始终
trim()输入字符串:消除首尾空格干扰分割逻辑; - ✅ 校验 token 数量与结构:确保恰好 3 个部分(左操作数、运算符、右操作数);
- ✅ 捕获
NumberFormatException并友好提示:比让程序崩溃更符合教学/用户体验需求; - ❌ 避免手动遍历字符提取数字:易出错且难以处理负数(如
"-5 + 3")、多位数或空格不规则情况;
⚠️ 注意:本方案适用于单运算符、无括号、无优先级的简单表达式(即“计算器入门级”需求)。若后续需支持 3 + 5 * 2 等含运算符优先级的表达式,应升级为递归下降解析器或使用工具库(如 JEP、exp4j),而非依赖 parseInt 或简单分割。
总结:parseInt 本身不是“解析表达式”的工具,而是“转换单个整数字符串”的基础方法;真正的表达式解析需要分词 + 类型转换 + 运算调度三步协同——理解这一职责边界,是写出可靠计算器的第一步。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










