
本文介绍如何将形如 "5 + 5" 的单字符串算术表达式安全拆分、解析数值与运算符,并完成基础四则运算,重点说明 Double.parseDouble() 的合理使用及输入校验策略。
本文介绍如何将形如 "5 + 5" 的单字符串算术表达式安全拆分、解析数值与运算符,并完成基础四则运算,重点说明 `double.parsedouble()` 的合理使用及输入校验策略。
在 Java 中,不存在 parseInt 方法的静态调用(如 Integer.parseInt() 是正确的,但 parseInt(...) 单独使用会编译错误),且对计算器类需求而言,仅用 int 类型易导致精度丢失或除法截断(例如 7 / 2 得 3 而非 3.5)。因此,推荐统一使用 Double.parseDouble() 解析操作数,兼顾整数与小数输入,并提升运算准确性。
以下是一个健壮、可扩展的简易表达式计算器实现:
public class Calculate {
public static void main(String[] args) {
// 测试用例
System.out.printf("%s = %.2f%n", "5 + 5", calculate("5 + 5"));
System.out.printf("%s = %.2f%n", "10.5 - 3", calculate("10.5 - 3"));
System.out.printf("%s = %.2f%n", "4 x 2.5", calculate("4 x 2.5"));
System.out.printf("%s = %.2f%n", "9 ÷ 4", calculate("9 ÷ 4"));
// 错误处理演示
try {
calculate("12 + 3 - 5"); // 格式不符
} catch (IllegalArgumentException e) {
System.out.println("❌ " + e.getMessage());
}
}
public static double calculate(String input) {
if (input == null || input.trim().isEmpty()) {
throw new IllegalArgumentException("输入不能为空");
}
String[] tokens = input.trim().split("\s+"); // 按空白字符分割(支持空格、制表符等)
if (tokens.length != 3) {
throw new IllegalArgumentException(
String.format("输入格式错误:需恰好 3 部分(如 '数字 运算符 数字'),当前共 %d 部分", 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 IllegalArgumentException("除数不能为零");
yield operand1 / operand2;
}
default -> throw new IllegalArgumentException(
"不支持的运算符: '" + operator + "'。请使用 +, -, *, /, x, ÷ 等符号"
);
};
} catch (NumberFormatException e) {
throw new IllegalArgumentException("数值格式错误:'" +
(e.getMessage().contains("For input string") ?
input : tokens[0] + " 或 " + tokens[2]) + "'");
}
}
}✅ 关键要点说明:
你是 TypeScript 项目架构专家,专注于脚手架搭建生产就绪的 Node.js 和前端应用。生成包含现代工具链(pnpm、Vite、Next.js)、类型
-
不依赖
parseInt:Integer.parseInt()无法处理小数,且异常信息不够友好;Double.parseDouble()更通用,失败时抛出NumberFormatException,便于统一捕获处理。 -
空格分割是核心技巧:
split("\s+")可可靠分离“操作数 运算符 操作数”,避免手动遍历字符串查找运算符的复杂逻辑。 - 强校验先行:检查空输入、token 数量、除零、非法数字格式,确保程序健壮性。
-
符号兼容性:支持英文与常见全角/数学符号(如
×,÷),提升用户体验。
⚠️ 注意事项:
立即学习“Java免费学习笔记(深入)”;
- 本实现仅支持二元运算(两个操作数 + 一个运算符),不支持多运算符表达式(如
"3 + 5 * 2")或括号。如需增强功能,应引入表达式解析器(如 Dijkstra 双栈算法或第三方库如 exp4j)。 - 生产环境建议封装
calculate()为Optional<double></double>返回类型,并配合日志记录异常细节。
掌握这种基于空格分词 + 类型安全解析的模式,是构建命令行计算器、配置脚本解析器等场景的坚实基础。

















