zoukankan      html  css  js  c++  java
  • # 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");
            }
        }
    }
    
    

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

    码云链接

  • 相关阅读:
    MySQL5.7初始密码查看及重置
    ps top kill
    Linux基础知识[2]【延迟及定时机制】
    大数加减运算
    字符串分隔
    打印NxN的矩阵
    交叉排序
    去除重复字符并排序
    大数求差——(华为实习招聘机试题)
    图解TCP-IP协议
  • 原文地址:https://www.cnblogs.com/nxy970408/p/6800836.html
Copyright © 2011-2022 走看看