栈的简单应用——四则运算(三)

本文详细阐述了如何使用Java语言解决包含括号的四则运算问题,通过两种方法进行求解:一种是采用符号入栈的方式,另一种是借鉴LISP语言的递归思路。程序实现了从输入中缀表达式到输出后缀表达式,再到计算最终结果的全过程,确保了运算的准确性和效率。

待解决问题

      如何计算带括号的四则运算?

解决方案

       一、采用符号入栈的解决方式,只是圆括号的操作方式会有所改变。圆括号的优先级最高,"("入栈后,只有遇到")"后才会出栈,并且要先弹出"("后的遗留操作符,保证"( )"中的表达式先被执行。"( )"中的加减乘除操作保持正常的栈处理方式。

      二、采用lisp解决问题的思路。所有的"( )"内的操作都是一样的,只不过处理的层次不一样,这时使用递归是一种很容易理解的方式。将每组"()"中的表达式看成子表达式,用相同的方法处理,将处理的结果拼接到父表达式维护的变量中。这种方式没有改变括号先行的原则。

代码实现

      我采用了第二种解决方案。

  • 符号优先级的初始化     

private  static Map<String,Integer> priorityMap = new HashMap<String,Integer>();
	private  static String symPattern = "";
	private Stack<String> stack = new Stack<String>();
	static{
		symPattern = "[+\\-*/]";
		priorityMap.put("+", -1);
		priorityMap.put("-", -1);
		priorityMap.put("*", 1);
		priorityMap.put("/", 1);
	}
  • 标准表达式输入

public String input(){
		Scanner scanner = new Scanner(System.in);
		String str = "";
		if(scanner.hasNext()){
			str += scanner.next();
		}
		System.out.println("the value of str = " + str);
		return str;
	}
  • 校验输入的表达式是否合法
public boolean checkInput(String input) throws Exception{
		char[] array = input.toCharArray();
		for(int i=0;i<array.length;i++){
			if(i<array.length - 1){
				String prev = String.valueOf(array[i]);
				String next = String.valueOf(array[i+1]);
				if(!prev.matches("[\\(\\)\\d\\.+\\-*/]")||!next.matches("[\\(\\)\\d\\.+\\-*/]")){
					throw new Exception("输入中含有非法字符,请重新输入!" );
				}else if(prev.matches("[\\.+\\-*/]")&&next.matches("[\\.+\\-*/]")){
					throw new Exception("输入了连续的符号!请重新输入!");
				}else if(prev.matches("/")&&next.matches("0")){
					throw new Exception("分母不能为零!");
				}
			}else{
				if(!String.valueOf(array[i]).matches("\\d")){
					throw new Exception("非法表达式");
				}
			}
		}
		return true;
	}

  • 将中缀表达式转换为后缀表达式

public String generateSuffixExp(String input) throws Exception{
		Stack<String> stack = new Stack<String>();
		char[] array = input.toCharArray();
		String suffix = "";
		int matchIndex = 0;
		for(int i = 0;i < array.length;i++){
			String atom = String.valueOf(array[i]);
			//括号先行,取得括号中的子表达式并获取其后缀表达式
			if(atom.equals("(")){
				//获取与左括号正确匹配的右括号索引
				matchIndex = this.matchIndex(input,i);
				//获取该组括号的中的子表达式
				String innerExp = input.substring(i+1, matchIndex);
				//获取子表达式的后缀表达式
				atom = generateSuffixExp(innerExp);
				i = matchIndex;
			}
			if(atom.matches(symPattern)){
				if(stack.isEmpty()){
					stack.push(atom);
				}else{
					
					while(!stack.isEmpty()&&priorityMap.get(stack.peek()) >= priorityMap.get(atom)){
						suffix += stack.pop();
					}
					
					stack.push(atom);
				}
			}else{
				while((i+1 < array.length)&&!(String.valueOf(array[i+1])).matches(symPattern)){
					atom += array[++i];
				}
				//atom是十以外的数字或非某组括号中的子表达式,将atom用原括号包装成一个整体
				if(atom.length() != 1&&!String.valueOf(atom.charAt(atom.length()-1)).matches(symPattern)){
					atom = "(" + atom +")";
				}
				suffix +=atom;
			}
		}
		while(!stack.isEmpty()){
			suffix += stack.pop();
		}
		return suffix;
	}
	public int matchIndex(String exp,int start) throws Exception{
		int count = 0;
		for(int i = start;i < exp.length();i++){
			char atom = exp.charAt(i);
			if(atom == '('){
				count++;
			}else if(atom == ')'){
				count--;
				if(count == 0){
					return i;
				}
			}
		}
		throw new Exception("wrong expression!");
	}

  • 计算后缀表达式

public String resuleCompute(String suffix){
		String result = "";
		for(int i=0;i<suffix.length();i++){
			String atom = String.valueOf(suffix.charAt(i));
			if(atom.matches("\\d")){
				stack.push(atom);
			}else if(atom.matches("\\(")){
				atom = "";
				while(!String.valueOf(suffix.charAt(++i)).equals(")")){
					atom += String.valueOf(suffix.charAt(i));
				}
				stack.push(atom);
			}else{
				float a = Float.parseFloat(stack.pop());
				float b = Float.parseFloat(stack.pop());
				float resultExp = this.getMiddleResult(a, b, atom);
				stack.push(""+resultExp);
			}
		}
		result = stack.pop();
		stack.clear();
		return result;
	}
	public float getMiddleResult(float a,float b,String symbol){
		if("+".equals(symbol)){
			return b + a;
		}else if("-".equals(symbol)){
			return b - a;
		}else if("*".equals(symbol)){
			return b * a;
		}else{
			return b / a;
		}
	}
  • 执行程序
public static void main(String[] args) throws Exception{
		Cal_Version_3 cal = new Cal_Version_3();
		while(true){
			String input = cal.input();
			if(cal.checkInput(input)){
				String suffix = cal.generateSuffixExp(input);
				System.out.println("the value of suffix is " + suffix);
				System.out.println(cal.resuleCompute(suffix));
			}
		}
	}
  • 执行结果
9+(3-1)*3+10/2
the value of str = 9+(3-1)*3+10/2
the value of suffix is 931-3*+(10)2/+
20.0

2.5+(2*(2.5+2))+2.5
the value of str = 2.5+(2*(2.5+2))+2.5
the value of suffix is (2.5)2(2.5)2+*+(2.5)+
14.0

结果讨论

     程序达到了预期的效果,但是还有很多工作要做,但基本目的已经达到了,已经了解了java实现表达式的四则运算。




源码地址: https://pan.quark.cn/s/d1f41682e390 miyoubiAuto 米游社每日米游币自动化Python脚本(务必使用Python3) 8更新:更换cookie的获取地址 注意:禁止在B站、贴吧、或各大论坛大肆传播! 作者已退游,项目不维护了。 如果有能力的可以pr修复。 小引一波 推荐关注几个非常可爱有趣的女孩! 欢迎B站搜索: @嘉然今天吃什么 @向晚大魔王 @乃琳Queen @贝拉kira 第方库 食用方法 下载源码 在Global.py中设置米游社Cookie 运行myb.py 本地第一次运行时会自动生产一个文件储存cookie,请勿删除 当前仅支持单个账号! 获取Cookie方法 浏览器无痕模式打开 http://user.mihoyo.com/ ,登录账号 按,打开,找到并点击 按刷新页面,按下图复制 Cookie: How to get mys cookie 当触发时,可尝试按关闭,然后再次刷新页面,最后复制 Cookie。 也可以使用另一种方法: 复制代码 浏览器无痕模式打开 http://user.mihoyo.com/ ,登录账号 按,打开,找到并点击 控制台粘贴代码并运行,获得类似的输出信息 部分即为所需复制的 Cookie,点击确定复制 部署方法--腾讯云函数版(推荐! ) 下载项目源码和压缩包 进入项目文件夹打开命令行执行以下命令 xxxxxxx为通过上面方式或取得米游社cookie 一定要用双引号包裹!! 例如: png 复制返回内容(包括括号) 例如: QQ截图20210505031552.png 登录腾讯云函数官网 选择函数服务-新建-自定义创建 函数名称随意-地区随意-运行环境Python3....
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值