用栈实现综合计算器

伪码描述

代码实现

package fun.xinghai.stack;

import java.util.Stack;

public class Calculator {

	public static void main(String[] args) {
		String expression = "173*24*2-55+12-517+36-41"; // = 7739
		//String expression = "7*2*2-5+1-5+3-4"; // = 18
		Stack<Integer> numStack = new Stack(); //数栈
		Stack<Character> opStack = new Stack(); //符号栈
		char ch = ' '; //用来存放遍历到的元素
		String keepNum = ""; //用来处理多位数
		
		for (int i = 0; i < expression.length(); i++) {
			ch = expression.charAt(i);
			if (isOper(ch)) {
				if (!opStack.isEmpty()) {
					if (priority(ch, opStack.peek()) <= 0) {
						numStack.push(cal(numStack.pop(), numStack.pop(), opStack.pop()));
					}
				}
				opStack.push(ch);
			} else {
				keepNum += ch;
				if (i == expression.length() - 1) {
					numStack.push(Integer.parseInt(keepNum));
				} else {
					if (isOper(expression.charAt(i + 1))) {
						numStack.push(Integer.parseInt(keepNum));
						keepNum = "";
					}
				}
			}
		}
		numStack.push(cal(numStack.pop(), numStack.pop(), opStack.pop()));
		System.out.println(expression + " = " + numStack.pop());
	}

	// 判断字符是否为运算符
	public static boolean isOper(char ch) {
		return ch == '+' || ch == '-' || ch == '*' || ch == '/';
	}

	// 判断两个运算符的优先级
	public static int priority(char ch1, char ch2) {
		if ((ch1 == '+' || ch1 == '-') && (ch2 == '*' || ch2 == '/'))
			return -1;
		if ((ch1 == '*' || ch1 == '/') && (ch2 == '+' || ch2 == '-'))
			return 1;
		return 0;
	}

	// 运算方法
	public static int cal(int a, int b, int op) {
		int res = 0;
		switch (op) {
		case '+':
			res = a + b;
			break;
		case '-':
			res = b - a;
			break;
		case '*':
			res = a * b;
			break;
		case '/':
			res = b / a;
			break;
		default:
			break;
		}
		return res;
	}

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值