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

本文详细阐述了如何使用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/0ed355622f0f 的源码改编 野火IM解决方案 野火IM是专业级即时通讯和实时音视频整体解决方案,由北京野火无限网络科技有限公司维护和支持。 主要特性有:私有部署安全可靠,性能强大,功能齐全,全平台支持,开源率高,部署运维简单,二次开发友好,方便与第方系统对接或者嵌入现有系统中。 详细情况请参考在线文档。 主要包括一下项目: 野火IM Vue Electron Demo,演示如何将野火IM的能力集成到Vue Electron项目。 前置说明 本项目所使用的是需要付费的,价格请参考费用详情 支持试用,具体请看试用说明 本项目默认只能连接到官方服务,购买或申请试用之后,替换,即可连到自行部署的服务 分支说明 :基于开发,是未来的开发重心 :基于开发,进入维护模式,不再开发新功能,鉴于已经终止支持且不再维护,建议客户升级到版本 环境依赖 mac系统 最新版本的Xcode nodejs v18.19.0 npm v10.2.3 python 2.7.x git npm install -g node-gyp@8.3.0 windows系统 nodejs v18.19.0 python 2.7.x git npm 6.14.15 npm install --global --vs2019 --production windows-build-tools 本步安装windows开发环境的安装内容较多,如果网络情况不好可能需要等较长时间,选择早上网络较好时安装是个好的选择 或参考手动安装 windows-build-tools进行安装 npm install -g node-gyp@8.3.0 linux系统 nodej...
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值