问题描述:
对于任意字符串,包含+ - * /和括号, 求出该表达式的值
首先百度该问题,网上有不少答案,但是实际思考,发现,很多答案没有考虑完全,例如:
-1+(-2)*3 遇到负号怎么办?
现贴出代码如下:
1 package calcultor;
2
3 import java.util.Stack;
4
5 public class Calcultor {
6
7 static boolean isNumber(char x) {
8 if (x >= '0' && x <= '9') {
9 return true;
10 }
11 return false;
12 }
13
14 static int priority(char x) {
15 if (x == '+' || x == '-') {
16 return 0;
17 } else if (x == '*' || x == '/') {
18 return 1;
19 } else if (x == '(' || x == ')') {
20 return -1;
21 } else if (x == '#') {
22 return -2;
23 }
24
25 return -3;
26 }
27
28 public static int calculte(String s) {
29 Stack<Integer> number = new Stack<Integer>();
30 Stack<Character> operate = new Stack<Character>();
31 char top;
32 int a = 0, b = 0;
33 int j = 0;
34 boolean flag = false;
35 for (int i = 0; i < s.length(); ++i) {
36 if (s.charAt(1) == '-') {
37 flag = true;
38 }
39 if (i >= 2 && i <= s.length() - 2) {
40 j = i;
41 if (!isNumber(s.charAt(j - 1)) && s.charAt(i) == '-' && isNumber(s.charAt(j + 1))) {
42 flag = true;
43 }
44 }
45 if (isNumber(s.charAt(i))) {
46 int Temp = 0;
47 String temp = "";
48 temp += s.charAt(i);
49 while (isNumber(s.charAt(++i)))
50 temp += s.charAt(i);
51 for (int jj = 0; jj < temp.length(); ++jj) {
52 Temp = Temp * 10 + temp.charAt(jj) - 48;
53 }
54 if (flag) {
55 Temp *= -1;
56 flag = !flag;
57 }
58 number.push(Temp);
59 temp = null;
60 }
61 if (!isNumber(s.charAt(i))) {
62 if (((s.charAt(i) == '-') && !flag) || (s.charAt(i) != '-')) {
63 if (operate.empty()) {
64 operate.push(s.charAt(i));
65 } else {
66 top = operate.peek();
67 if (priority(s.charAt(i)) > priority(top) || s.charAt(i) == '(') {
68 operate.push(s.charAt(i));
69 } else {
70 while (priority(s.charAt(i)) <= priority(top)) {
71 if (top == '#' && s.charAt(i) == '#') {
72 int answer;
73 operate.pop();
74 answer = number.peek();
75 number.pop();
76 return answer;
77 } else if (top == '(' && s.charAt(i) == ')') {
78 ++i;
79 } else {
80 a = number.peek();
81 number.pop();
82 b = number.peek();
83 number.pop();
84 }
85 if (top == '+') {
86 b += a;
87 number.push(b);
88 } else if (top == '-') {
89 b -= a;
90 number.push(b);
91 } else if (top == '*') {
92 b *= a;
93 number.push(b);
94 } else if (top == '/') {
95 b /= a;
96 number.push(b);
97 }
98 operate.pop();
99 top = operate.peek();
100 }
101 operate.push(s.charAt(i));
102 }
103 }
104 }
105 }
106 }
107
108 return 0;
109 }
110
111 public static void main(String[] args) {
112 String s = new String("#(1+2)+6/3+(-2*2)+(-2*6)#");
113 int answer = calculte(s);
114 System.out.println("the answer is " + answer);
115 }
116 }