• # 20155224 第十一周 课堂练习《计算后缀表达式的值》


    20155224 第十一周 课堂练习《计算后缀表达式的值》

    代码实现

    操作数和运算符的入栈与计算如下:

    //如果是运算符,调用isOperator
                if (isOperator(token)) {
                    op2=(stack.pop()).intValue();//从栈中弹出操作数2
                    op1=(stack.pop()).intValue();//从栈中弹出操作数1
                    result=evalSingleOp(token.charAt(0),op1,op2);//根据运算符和两个操作数调用evalSingleOp计算result;
                    stack.push(new Integer(result));//计算result入栈;
                }
                else {
                    //如果是操作数
                    stack.push(new Integer(Integer.parseInt(token)));// 操作数入栈;
                }
    
            }
            return result;
        }
    
    

    检测到运算符后,将op1和op2出栈并进行运算。如果不是运算符,将数字入栈。

    其他部分如蓝墨云上已给出部分。

    检测

    检测代码如下

    public class MyDCTester {
        public static void main(String[] args) {
            String expression, again;
            int result;
            try {
                Scanner in = new Scanner(System.in);
                do {
    
                    MyDC evaluator = new MyDC();
                    System.out.println("Enter a valid postfix expression: ");
                    expression = in.nextLine();
                    result = evaluator.evaluate(expression);
                    System.out.println();
                    System.out.println("That expression equals " + result);
                    System.out.print("Evaluate another expression [Y/N]? ");
                    again = in.nextLine();
                    System.out.println();
    
                } while (again.equalsIgnoreCase("y"));
            } catch (Exception IOException) {
                System.out.println("Input exception reported");
            }
        }
    }
    
    

    简单测试了加法、乘法的计算情况,和非法输入的情况。

    码云链接

  • 相关阅读:
    3.2 线程复用:线程池
    3.1.7 线程阻塞工具类:LockSupport
    3.1.6 循环栅栏:CyclicBarrier
    3.1.4 读写锁
    3.1.5 倒计时器:CountDownLatch
    3.1.3 允许多个线程同时访问:信号量
    3.1.2 condition 条件
    3.1.1 重入锁 以及源码分析
    2.8.4 错误的加锁
    jsp中 scope="application" 表示
  • 原文地址:https://www.cnblogs.com/nxy970408/p/6800836.html
Copyright © 2020-2023  润新知