zoukankan      html  css  js  c++  java
  • 第九周(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;  
            }  
        } 
    }

    最终运行结果如下:

      

  • 相关阅读:
    PHP学习——数组处理函数(一)
    PHP与MySQL的连接
    c语言:<tchar.h>
    PHP数组(二)
    PHP数组(一)
    PHP基础知识(三)
    Git和GitHub
    PHP基础知识(二)
    js 全选和反选(复选框)
    python 字典之删除
  • 原文地址:https://www.cnblogs.com/YangXiaomoo/p/6058211.html
Copyright © 2011-2022 走看看