Stack (single digit calculator)

method:

Judgment priority

Determine whether a character or a number

calculation method

View the top element of the stack

train of thought

Code for single digit calculator:

package calculator;

public class Calculator {
	public static void main(String[] args) {
		String exp = "78*9-2";
		Stack num = new Stack(10);
		Stack ope = new Stack(10);
		int index = 0;
		int num1 = 0;
		int num2 = 0;
		char oper = ' ';
		int res = 0;
		char ch = ' ';
		String keepNum = "";
		while(true) {
			ch = exp.substring(index, index+1).charAt(0);
			if(ope.isOper(ch)) {
				if(!ope.isEmpty()){
					if(ope.priority(ch) <= ope.priority(ope.peak())) {
						num1 = num.pop();
						num2 = num.pop();
						oper = (char) ope.pop();
						res = num.cal(num1, num2, oper);
						num.push(res);
						ope.push(ch);
					}else {
						ope.push(ch);
					}
				}else {
					ope.push(ch);
				}
			}else {
//				num.push(ch - 48);
				keepNum+=ch;
				if(index == exp.length() - 1) {
					num.push(Integer.parseInt(keepNum));
				}else {
					if(ope.isOper(exp.substring(index+1,index+2).charAt(0))) {
						num.push(Integer.parseInt(keepNum));
						keepNum="";
					}
				}
			}
			index++;
			if(index >= exp.length()) {
				break;
			}
		}
		while(true) {
			if(ope.isEmpty()) {
				break;
			}
			num1 = num.pop();
			num2 = num.pop();
			oper = (char) ope.pop();
			res = num.cal(num1, num2, oper);
			num.push(res);
		}
		System.out.printf("表达式%s=%d",exp,num.pop());
	}

}
class Stack{
	private int maxSize;
	private int[] stack;
	private int top = -1;
	
	public Stack(int maxsize) {
		this.maxSize = maxsize;
		stack = new int[maxsize];
	}
	
	public boolean isFull() {
		return top == maxSize - 1;
	}
	
	public boolean isEmpty() {
		return top == -1;
	}
	
	public void push(int value) {
		if(isFull()) {
			System.out.println("栈满!");
			return;
		}
		top++;
		stack[top] = value;
	}
	
	public int pop() {
		if(isEmpty()) {
			System.out.println("栈空!");
			return -1;
		}
		int value = stack[top];
		top--;
		return value;
	}
//	public void list() {
//		if(isEmpty()) {
//			System.out.println("栈空!");
//			return;
//		}
//		for(int i = top; i >= 0; i--) {
//			System.out.println(stack[i]);
//		}
//	}
	//优先级
	public int priority(int oper) {
		if(oper == '*' || oper == '/') {
			return 1;
		}else if(oper == '+' || oper == '-') {
			return 0;
		}else {
			return -1;
		}
	}
	//判断是不是运算符
	public boolean isOper(char val) {
		return val == '+' || val == '-' || val == '*' || val == '/';
	}
	//查看栈顶
	public int peak() {
		return stack[top];
	}
	//计算
	public int cal(int num1, int num2, char 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;
	}
}

Guess you like

Origin blog.csdn.net/qq_56127002/article/details/131550902