欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-15 19:05:41
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 opera = new Stack();Stack num = new St...
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;
	}
}

本文地址:https://blog.csdn.net/weixin_45829957/article/details/107591468

相关标签: 数据结构