JAVA 实现简单四则运算

…衆ロ難τιáo~ 提交于 2019-11-26 17:46:22

利用栈的先进后出的特点,遍历运算表达式依次得到expression的每一个字符分别按规则加入符号栈和数字栈:
1.1 如果符号栈为空直接push
1.2 如果栈不为空 判断优先级 如果当前符号优先级高,直接push ,否则将数字栈的栈顶两个元素 pop,并将符号栈栈顶的符号进行运算得到的结果在push进数字栈。
2.1 如果是数字,要看后面的是数字还是表达式 即多位数的情况要予以考虑。
注意:
1、两个数进行减法运算的时候,要让栈顶元素做被减数。
2、数字的判断退出循环要记得Index–,否则会越界


public class Calculator extends ArrStack{
	public Calculator() {
		super(100);
	}
	public static void main(String[] args) {
		String expression = "200*2+2*10-1";
		Calculator calculator1= new Calculator();
		Calculator calculator2= new Calculator();
		int index = 0;
		int res  = 0;
		char ch = ' ';
		int c = 0;
		String str = "";
		while(true) {
			//依次得到expression的每一个字符
			ch = expression.substring(index, index + 1).charAt(0);
			//判断 ch 是什么,并作出相应的处理
			if(calculator1.Isoper(ch)) {  //运算符
				if(calculator1.IsEmpty()) {  //符号栈为空
					calculator1.push(ch);  //直接push 
				}else {      // 判断优先级
					if(priorty(calculator1.pick()) <priorty(ch) ){  //当前优先级高
						calculator1.push(ch);  //直接push 
					}else {
						res = calculator1.cal( calculator2.pop(),  calculator2.pop(),  calculator1.pop()); 
						calculator2.push(res);
						calculator1.push(ch);
					}
				}
			}else {  //如果是数字,要看后面的是数字还是表达式
				if(index == expression.length() - 1) {
					calculator2.push(Integer.parseInt(expression.substring(index, index + 1)));
					break;
				}else { 
					while(true) {
						if(calculator1.Isoper(expression.substring(index, index + 1).charAt(0))) {
							index --;
							break;
						}else{
							str = str +  expression.substring(index, index + 1);
						}
						index ++;
					}
					c = Integer.parseInt(str);
					calculator2.push(c);  //char --> int
					str = "";
				}
			}
			index ++;
			if(index >= expression.length()) {
				break;
			}
		}
		while(!calculator1.IsEmpty()) {
			res = calculator1.cal( calculator2.pop(),  calculator2.pop(),  calculator1.pop()); 
			calculator2.push(res);
		}
		System.out.println(res);
	}
	
	//返回运算及的优先顺序,数字越大,优先级最高
	public static int priorty(int i) {
		if(i == '*' || i == '/') {
			return 1;
		}else if(i == '+' || i == '-') {
			return 0;
		}else {
			return -1;
		}
	}
	
	//判断是不是运算符
	public boolean Isoper(char val) {
		return val =='+' ||val =='-' || val == '*' || val =='/';
	}
	//计算方法
	public int cal  (int num1, int num2,int i) {
		int res = 0; 
		if(i== '+') {
			res =num1 + num2;
		}else if(i== '-') {
			res =num2 - num1;
		}else if(i== '*') {
			res =num1 * num2;
		}else if(i== '/') {
			res =num1 / num2;
		}
		return res;
	}
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!