java栈实现简易计算器算法问题描述:
对于任意字符串,包含+ - * /和括号,求出该表达式的值
⾸先百度该问题,⽹上有不少答案,但是实际思考,发现,很多答案没有考虑完全,例如:
-1+(-2)*3 遇到负号怎么办?
现贴出代码如下:
1package calcultor;
2
3import java.util.Stack;
4
5public class Calcultor {
6
7static boolean isNumber(char x) {
8if (x >= '0' && x <= '9') {
9return true;
10 }
11return false;
12 }
13
14static int priority(char x) {
15if (x == '+' || x == '-') {
16return 0;
17 } else if (x == '*' || x == '/') {
18return 1;
19 } else if (x == '(' || x == ')') {
20return -1;
21 } else if (x == '#') {
22return -2;
23 }
24
25return -3;
26 }
27
28public static int calculte(String s) {
29 Stack<Integer> number = new Stack<Integer>();
30 Stack<Character> operate = new Stack<Character>();
31char top;
32int a = 0, b = 0;
33int j = 0;
34boolean flag = false;
35for (int i = 0; i < s.length(); ++i) {
36if (s.charAt(1) == '-') {
37 flag = true;
38 }
39if (i >= 2 && i <= s.length() - 2) {
40 j = i;
41if (!isNumber(s.charAt(j - 1)) && s.charAt(i) == '-' && isNumber(s.charAt(j + 1))) {
42 flag = true;
43 }
44 }
45if (isNumber(s.charAt(i))) {
46int Temp = 0;
47 String temp = "";
48 temp += s.charAt(i);
49while (isNumber(s.charAt(++i)))
50 temp += s.charAt(i);
51for (int jj = 0; jj < temp.length(); ++jj) {
52 Temp = Temp * 10 + temp.charAt(jj) - 48;
53 }
54if (flag) {
55 Temp *= -1;
56 flag = !flag;
57 }
58 number.push(Temp);
59 temp = null;
60 }
61if (!isNumber(s.charAt(i))) {
62if (((s.charAt(i) == '-') && !flag) || (s.charAt(i) != '-')) {
63if (pty()) {
64 operate.push(s.charAt(i));
65 } else {
66 top = operate.peek();
67if (priority(s.charAt(i)) > priority(top) || s.charAt(i) == '(') {
用java编写一个简单的计算器68 operate.push(s.charAt(i));
69 } else {
70while (priority(s.charAt(i)) <= priority(top)) { 71if (top == '#' && s.charAt(i) == '#') {
72int answer;
73 operate.pop();
74 answer = number.peek();
75 number.pop();
76return 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 }
85if (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
108return 0;
109 }
110
111public static void main(String[] args) {
112 String s = new String("#(1+2)+6/3+(-2*2)+(-2*6)#");
113int answer = calculte(s);
114 System.out.println("the answer is " + answer);
115 }
116 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论