//解析表达式
public static String getResult(String expr) throws Exception {
try {
System.out.println("计算"+expr);
/*数字栈*/
Stack<BigDecimal> number = new Stack<BigDecimal>();
/*符号栈*/
Stack<String> operator = new Stack<String>();
operator.push(null);// 在栈顶压人一个null,配合它的优先级,目的是减少下面程序的判断
/* 将expr打散为运算数和运算符 */
Pattern p = Pattern.compile("(?<!\\d)-?\\d+(\\.\\d+)?|[+\\-*/()]");// 这个正则为匹配表达式中的数字或运算符
Matcher m = p.matcher(expr);
while(m.find()) {
String temp = m.group();
if(temp.matches("[+\\-*/()]")) {//遇到符号
if(temp.equals("(")) {//遇到左括号,直接入符号栈
operator.push(temp);
System.out.println("符号栈更新:"+operator);
}else if(temp.equals(")")){//遇到右括号,"符号栈弹栈取栈顶符号b,数字栈弹栈取栈顶数字a1,数字栈弹栈取栈顶数字a2,计算a2 b a1 ,将结果压入数字栈",重复引号步骤至取栈顶为左括号,将左括号弹出
String b = null;
while(!(b = operator.pop()).equals("(")) {
System.out.println("符号栈更新:"+operator);
BigDecimal a1 = number.pop();
BigDecimal a2 = number.pop();
System.out.println("数字栈更新:"+number);
java 字符串表达式计算值
最新推荐文章于 2024-03-22 18:19:03 发布
本文介绍如何在Java中解析和计算字符串表达式的值,涉及字符串到数学表达式的转换及运算符优先级处理。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



