第九周(11.11-11.17)----结对项目----计算后缀表达式

  为了计算由前缀表达式转换过来的后缀表达式,我编写了方法public int countback(String src)。

  思想是把后缀表达式转型成字符串,用该方法接受字符串后,将src[i]依次存如栈中。

    如果src[i]不是操作符就直接入栈;

    如果是操作符就取栈顶前两个元素进行运算,并把结果入栈。

    最后栈顶元素的值就是表达式的值。

  这里的计算我编写了public int count(String a, String b, String e),用以返回计算结果。

public int countback(String src):

 1 public int countback(String src) {  
 2             Stack<String> stack = new Stack<String>();  
 3             for (int i = 0; i < src.length(); i++) {  
 4                 String foo = src.charAt(i) + "";  
 5                 if (!isoperator(foo)) {  
 6                     stack.push(foo);  
 7                 } else {//如果是运算符  
 8                     // 取栈顶两元素进行计算,并将计算结果放入栈顶  
 9                     String a = stack.pop();  
10                     String b = stack.pop();  
11                     int temp = count(b, a, foo);  
12                     stack.push(temp + "");  
13       
14                 }  
15             }  
16             return Integer.parseInt(stack.pop());//最后栈顶元素的值就是表达式的值了  
17         }  

public int count(String a, String b, String e):

public int count(String a, String b, String e) {  
        int temp1 = Integer.parseInt(a);  
        int temp2 = Integer.parseInt(b);  
        if ("+".equals(e)) {  
            return temp1 + temp2;  
        } else if ("-".equals(e)) {  
            return temp1 - temp2;  
        } else if ("*".equals(e)) {  
            return temp1 * temp2;  
        } else {  
            return temp1 / temp2;  
        }  
    } 
}

最终运行结果如下:

 

  

转载于:https://www.cnblogs.com/YangXiaomoo/p/6058211.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值