双栈实现基本计算器
public class StackCalculator {
public static void main(String[] args) {
StackCalculatorTest stackCalculatorTest = new StackCalculatorTest();
System.out.println(stackCalculatorTest.calculation("7*2*2-5+1-5+3-4"));
}
}
class StackCalculatorTest {
private Stack<Integer> stack1;
private Stack<Character> stack2;
public StackCalculatorTest() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public int priority(char c) {
if (c == '+' || c == '-') {
return 1;
}
if (c == '*' || c == '/') {
return 2;
}
return 0;
}
public int switch_(char c1, int num2, int num1) {
int temp = 0;
switch (c1) {
case '*':
temp = num1 * num2;
break;
case '-':
temp = num1 - num2;
break;
case '+':
temp = num1 + num2;
break;
case '/':
temp = num1 / num2;
break;
}
return temp;
}
public int calculation(String s) {
char[] chars = s.toCharArray();
for (char c : chars) {
if (c == '+' || c == '-' || c == '*' || c == '/') {
if (stack2.size() != 0) {
if (priority(c) <= priority(stack2.peek())) {
int num1 = stack1.pop();
int num2 = stack1.pop();
char c1 = stack2.pop();
stack1.push(switch_(c1, num1, num2));
}
}
stack2.push(c);
}
if (c >= '0' && c <= '9') {
Integer num = Integer.parseInt(String.valueOf(c));
stack1.push(num);
}
}
while (!stack2.isEmpty()){
int num1 = stack1.pop();
int num2 = stack1.pop();
char c1 = stack2.pop();
stack1.push(switch_(c1,num1,num2));
}
return stack1.peek();
}
}