(转载)栈
package sweexamination.level1;
import java.util.*;
import java.util.regex.*;
import java.lang.*;
public class AA {
/**
* @param args
*/
/*
* 在回答你的问题之前 做两个说明! 1. 你的输入要合法(不含字母,运算符后有且必须有数字,中间不能有空格)
*/
static String[] operater = new String[20];
static String[] number = new String[20];
public int countExpression(String str) {
Stack countStack1 = new Stack();
Stack countStack2 = new Stack();
int result = 0;
number = str.split("\\/|\\*|\\+|\\-");
operater = str.split("\\d+");
for (int i = 0; i < number.length; i++) {
countStack1.push(number[i]);
if (i != number.length - 1) {
countStack1.push(operater[i + 1]);
}
}
while (!countStack1.isEmpty())
countStack2.push(countStack1.pop());
String op;
while (!countStack2.isEmpty()) {
result = 0;
op = countStack2.pop().toString();
if (op.equals("*")) {
result = Integer.parseInt(countStack1.pop().toString())
* Integer.parseInt(countStack2.pop().toString());
countStack1.push(result);
continue;
}
if (op.equals("/")) {
result = Integer.parseInt(countStack1.pop().toString())
/ Integer.parseInt(countStack2.pop().toString());
countStack1.push(result);
continue;
}
countStack1.push(op);
}
while (!countStack1.isEmpty())
countStack2.push(countStack1.pop());
while (!countStack2.isEmpty()) {
result = 0;
op = countStack2.pop().toString();
if (op.equals("+")) {
result = Integer.parseInt(countStack1.pop().toString())
+ Integer.parseInt(countStack2.pop().toString());
countStack1.push(result);
continue;
}
if (op.equals("-")) {
result = Integer.parseInt(countStack1.pop().toString())
- Integer.parseInt(countStack2.pop().toString());
countStack1.push(result);
continue;
}
countStack1.push(op);
}
return result;
// System.out.println(result);
}
public static void main(String[] args) {
int num;
AA ct = new AA();
num = ct.countExpression("1+2*6-12+5*2");
System.out.println(num);
}
}