stack(栈)中缀表达式实现计算机加法(括号运算符未考虑)

在这里插入图片描述

import java.util.Stack;

public class Calculate {
	public static void main(String[] args) {
		String test = "70+2*5-3";
		String sum = null;
		char ch = ' ';
		Stack<Character> opera = new Stack<Character>();
		Stack<Integer> num = new Stack<Integer>();
		int index = 0;
		int num1 = 0;
		int num2 = 0;
		int oper = 0;
		int res = 0;
		String keepNum = "";
		while (true) {
			ch = test.substring(index, index + 1).charAt(0);
//			System.out.println(ch);
			if (!isOper(ch)) {
				keepNum += ch;
				if (index == test.length() - 1) {
					num.push(Integer.parseInt(keepNum));
//					System.out.println(ch - 48);
				}
				else if (isOper(test.substring(index + 1, index + 2).charAt(0))) {
					num.push(Integer.parseInt(keepNum));
					
//					System.out.println(keepNum+ " 二位数结果"+(keepNum - 48));
					keepNum = "";
				}
			} else {
				if (opera.empty()) {
					opera.push(ch);
				} else if (priority(ch) <= priority(opera.peek())) {
					num1 = num.pop();
					num2 = num.pop();
					oper = opera.pop();
					res = cal(num1, num2, oper);
					num.push(res);
					opera.push(ch);
				} else {
					opera.push(ch);
				}
			}

			index++;
			if (index >= test.length()) {
				break;
			}
		}
		while (true) {
			if (opera.empty()) {
				break;
			}
			num1 = num.pop();
			num2 = num.pop();
			oper = opera.pop();
			res = cal(num1, num2, oper);
			num.push(res);
		}
		System.out.println("计算结果为" + num.peek());
	}

	public static boolean isOper(char val) {
		return val == '+' || val == '-' || val == '*' || val == '/';
	}

	public static int priority(int result) {
		if (result == '*' || result == '/') {
			return 1;
		} else if (result == '+' || result == '-') {
			return 0;
		} else {
			return -1; // 假定目前的表达式只有 +, - , * , /
		}
	}

	public static int cal(int num1, int num2, int oper) {
		int res = 0;
		switch (oper) {
		case '+':
			res = num1 + num2;
			break;
		case '-':
			res = num2 - num1;// 注意顺序
			break;
		case '*':
			res = num1 * num2;
			break;
		case '/':
			res = num2 / num1;
			break;
		default:
			break;
		}
		return res;
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只猪的思考

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值