20-12-17 基於棧做一個計算器
阿新 • • 發佈:2020-12-18
技術標籤:java
package Stack;
public class Calculator {
public static void main(String[] args) {
String expression = "7*3+3*6-3+1";
ArrayStack2 numberStack = new ArrayStack2(10);
ArrayStack2 operStack = new ArrayStack2(10);
int index = 0;
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' '; //用於儲存掃描到的數字
String keepNum = ""; //方便兩位數的運算,用以拼接字串
while (true) {
ch = expression.substring(index, index + 1).charAt(0);
if (operStack.isOper(ch)) {
if (!operStack.isEmpty()) {
if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
num1 = numberStack.pop();
num2 = numberStack.pop();
oper = operStack.pop();
res = numberStack. cal(num1, num2, oper);
numberStack.push(res);
operStack.push(ch);
} else {
operStack.push(ch);
}
} else {
operStack.push(ch);
}
} else {
keepNum += ch;// 這個是字串的拼接
if (index == expression.length() - 1) {
numberStack.push(Integer.parseInt(keepNum)); //直接呼叫包裝類的方法,轉變成Int型
} else {
if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {
numberStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if (index >= expression.length()) {
break;
}
}
while (true) {
//如果符號棧為空,則計算到最後的結果, 數棧中只有一個數字【結果】
if (operStack.isEmpty()) {
break;
}
num1 = numberStack.pop();
num2 = numberStack.pop();
oper = operStack.pop();
res = numberStack.cal(num1, num2, oper);
numberStack.push(res);//入棧
}
//將數棧的最後數,pop出,就是結果
int res2 = numberStack.pop();
System.out.printf("表示式 %s = %d", expression, res2);
}
}
class ArrayStack2 {
private int maxSize;
private int[] stack;
private int top = -1;
public ArrayStack2(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize]; //這裡其實是覆蓋了之前的陣列長度
}
//判斷棧滿 是在ArrayStack內部的方法,所以可以直接呼叫內部的引數 只要有返回數就是有返回值的,這裡是布林數
public boolean isFull() {
return top == maxSize - 1;
}
public boolean isEmpty() {
return top == -1;
}
//向棧中新增數 push
public void push(int merber) {
if (isFull()) {
System.out.println("棧滿,新增失敗");
} else {
stack[++top] = merber;
}
}
//棧中彈出數 當需要有返回值的時候,需要返回異常
public int pop() {
int temp;
if (isEmpty()) {
throw new RuntimeException("棧滿,彈出失敗");
} else {
temp = stack[top--];
return temp;
}
}
public void show() {
if (isEmpty()) {
System.out.println("棧空");
return;
} else {
for (int i = 0; i < top; i++) {
System.out.printf(" %d ", 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 peek() {
return stack[top];
}
//計算的方法
public int cal(int num1, int num2, int oper) {
int res = 0;
switch (oper) {
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
default:
break;
}
return res;
}
}