逆波兰计算器的实现与分析

在这里插入图片描述图来自该视频中讲师的分析,实现代码如下:

在这里插入代码片package stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class PolandNo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//先定义逆波兰表达式
		//(3+4)*5-6 => 3 4 + 5 * 6 -
		//说明为了方便,逆波兰表达式的数字和符号使用空格隔开
		String suffixExpression = "3 4 + 5 * 6 -";
		//思路 1、将 表达式放到ArrayList中
		//2、将ArrayList 配合栈完成计算
		
		List<String> rpnList = getListString(suffixExpression);
		System.out.println("rpnList=" + rpnList);
		
		int res = cal(rpnList);
		System.out.println("输出结果为:"+res);
	}
	
	public static List<String> getListString(String suffixExpression){
		//将字符串以空格为标识 隔开取数进list
		String[] split = suffixExpression.split(" ");
		List<String> List = new ArrayList<String>();
		for(String ele: split) {
			List.add(ele);
		}
		return List;
	}
	//完成对逆波兰表达式的运算
	public static int cal(List<String> ls) {
		Stack<String> stack = new Stack<String>();
		for(String item:ls) {
			 //正则表达式取出数
			if(item.matches("\\d+")) {	
				 stack.push(item);
				}else {
				 //pop出两个数并运算
					int num2 = Integer.parseInt(stack.pop().trim());//讲师所写的代码为int num2 = Integer.parseInt(stack.pop());但是代码运行后会编译错误,具体原因这篇博客有分析(非本人博客):[关于Exception in thread "main" java.lang.NumberFormatException: For input string: " 1 "的原因和解决方法](https://blog.csdn.net/weixin_44089360/article/details/104683806)
					int num1 = Integer.parseInt(stack.pop().trim());
					int res = 0;
					if(item.equals("+")) {
						res = num1 + num2;
					}else if(item.equals("-")) {
						res = num1 - num2;
					}else if(item.equals("*")) {
						res = num1 * num2;
					}else if(item.equals("/")) {
						res = num1 / num2;
					}else {
						throw new RuntimeException("运算符有误");
					}
					stack.push(" " + res);
				}
		  }
		 return Integer.parseInt(stack.pop().trim());
	}
	

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值