关于括号的优先级这一块还没有完成,目前只支持简单的四则运算。

相关代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.util.Stack;

public class PostfixExpression {

// 中缀表达式转化为后缀表达式
public String suffix(String infix) {
infix = infix.replaceAll(" ", "");
StringBuffer suffixExpression = new StringBuffer();
char[] chars = infix.toCharArray();
String[] letters = new String[chars.length];
for (int i = 0; i < letters.length; i++) {
letters[i] = String.valueOf(chars[i]);
}
Stack<String> stack = new Stack<String>();
for (int i = 0; i < letters.length; i++) {
if (letters[i].matches("^[0-9]*$")) {
if (i > 1 && letters[i - 1].matches("^[0-9]*$")) {
suffixExpression.append(letters[i]);
} else {
suffixExpression.append(" " + letters[i]);
}
} else {
// 表达式的判断
if ("(".equals(letters[i])) {
stack.push("(");
} else if (")".equals(letters[i])) {
String s = stack.pop();
while (!"(".equals(s)) {
suffixExpression.append(" " + s + " ");
s = stack.pop();
}
} else {
if (stack.isEmpty()) {
stack.push(letters[i]);
} else {
String top = stack.firstElement();
if (("-".equals(top) || "+".equals(top)) && ("x".equals(letters[i])) || "/".equals(letters[i])) {
stack.push(letters[i]);
} else {
while (!(("-".equals(top) || "+".equals(top)) && ("x".equals(letters[i])) || "/".equals(letters[i]))) {
suffixExpression.append(" " + stack.pop() + " ");
if (stack.isEmpty()) {
break;
} else {
top = stack.firstElement();
}
}
stack.push(letters[i]);
}
}
}
}
}
while (!stack.isEmpty()) {
suffixExpression.append(" " + stack.pop() + " ");
}
return suffixExpression.toString();
}

// 计算后缀表达式
public double calculate(String expression) {
Stack<String> stack = new Stack<String>();
String[] values = expression.split(" {1,}");
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (value.matches("^[0-9]*$")) {
stack.push(value);
} else {
try {
stack.push(this.calculate(stack.pop(), stack.pop(), value));
} catch (Exception e) {
System.out.println("输入的表达式有误");
}
}
}
return Double.valueOf(stack.pop());
}

// 计算两个数的值
private String calculate(String s2, String s1, String operator) throws Exception {
double num1 = Double.valueOf(s1);
double num2 = Double.valueOf(s2);
double num;
if ("+".equals(operator)) {
num = num1 + num2;
} else if ("x".equals(operator)) {
num = num1 * num2;
} else if ("-".equals(operator)) {
num = num1 - num2;
} else if ("/".equals(operator)) {
num = num1 / num2;
} else {
throw new Exception("Can't explain this operator");
}
return String.valueOf(num);
}

public static void main(String[] args) {
PostfixExpression p = new PostfixExpression();
String expression = "1x100+90x2/2+2";
String suffixExpression = p.suffix(expression);
System.out.println(suffixExpression);
System.out.println(p.calculate(suffixExpression));
}

}

理论支撑: