后缀表达式计算(Java栈练习)

栈结构是解决后缀表达式的一种很好的思路,基本思路就是,输入你要计算的表达式,挨个遍历,遇到数字就将他们压入栈中,遇到运算符再依次从栈中弹出两个数字,我们要保证数字的顺序,特别是计算除法和减法的时候更要注意。

其次,因为运算数可能为负数,在字符串检测时,是无法将-3正确识别为负三的,所以在这里要额外处理负数符号。

最后添加try,catch语句,能正确显示输入当中的错误。

package 数据结构;

import java.util.Scanner;
import java.util.Stack;

public class Stack_test {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out,println("请正确输入后缀表达式,中间用空格相隔(例:4 7 -3 * -):");
		String str = in.nextLine();
		//创建对象
		CalculateDemo cal = new CalculateDemo(str);
		//调用相关方法
		cal.calculate();
	}
}

class CalculateDemo{
	private String str;

	public CalculateDemo(String str) {
		super();
		this.str = str;
	}
	
	public void calculate() {
		if(!examine(str))
			System.out.println("输入字符串中包含非法字符,无法识别!");
		else {
			//创建Stack类对象,指定范型
			Stack<Integer> stack = new Stack<Integer>();
			//循环依次遍历每一个元素
			try {
				for(int i = 0;i < str.length();i++) {
					//若是数字就进行压栈
					if('0' < str.charAt(i) && str.charAt(i) < '9') {
						stack.push((int)(str.charAt(i)-'0'));
					}
					//遇到运算符就弹出两个数据,注意数据先后顺序
					else if(str.charAt(i) == '+'){
						int y = stack.pop();
						int x = stack.pop();
						int z = x+y;
						stack.push(z);
					}
					//减法要额外考虑,因为数据可能会是负数
					else if(str.charAt(i) == '-'){
						if(i == (str.length()-1) || str.charAt(i+1) == ' ') {
							int y = stack.pop();
							int x = stack.pop();
							int z = x-y;
							stack.push(z);
						}
						else if('0' < str.charAt(i+1) && str.charAt(i+1) < '9') {
							stack.push(((int)(str.charAt(i+1)-'0')*-1));
							i++;
						}
					}
					else if(str.charAt(i) == '*'){
						int y = stack.pop();
						int x = stack.pop();
						int z = x*y;
						stack.push(z);
					}
					else if(str.charAt(i) == '/'){
						int y = stack.pop();
						int x = stack.pop();
						int z = x/y;
						stack.push(z);
					}
					i++;
				}
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();

			}
			System.out.println(stack.pop());
		}
	}
	//用于检验字符串是否包含非法字符
	public boolean examine(String temp) {
		for(int i = 0;i < temp.length();i++) {
			if('0' < temp.charAt(i) && temp.charAt(i) < '9')
				continue;
			else if(temp.charAt(i) == '+')
				continue;
			else if(temp.charAt(i) == '-')
				continue;
			else if(temp.charAt(i) == '*')
				continue;
			else if(temp.charAt(i) == '/')
				continue;
			else if(temp.charAt(i) == ' ')
				continue;
			else 
				return false;
		}
		return true;
	}
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值