The calculation of arithmetic expression is mainly a two-step operation
The first step is to convert infix expressions into postfix expressions . Refer to the "Data structure and algorithm analysis--c language description" of the freshman year, 3.3.3 the textbook, complete the following code:
Staticstring Mid_to_suf (String str) {Stack<Character> s =NewStack<character>(); String Suf=NewString (); HashMap<character, integer> map =NewHashmap<character, integer>(); Map.put (' + ', 1);//set the precedence of an operatorMap.put ('-', 1); Map.put (' * ', 2); Map.put ('/', 2); Map.put (' (', 3); for(inti = 0; I < str.length (); i++){ Charc =Str.charat (i); if(c = = ' = ')) Break; if(c = = "| | (c >= ' 0 ' && C <= ' 9 ')) Suf+=C; Else if(c = = ' (') S.push (c); Else if(c = = ') '){ while(!S.isempty ()) { CharOP =S.pop (); if(Op = = ' (') Break; Suf+=op; } } Else { if(S.isempty ()) S.push (c); Else { while(!S.isempty ()) { CharOP =S.peek (); if(Op = = ' (') Break; if(Map.get (OP) <Map.get (c)) Break; Else{s.pop (); Suf+=op; }} s.push (c); } } } while(!s.isempty ()) Suf+=S.pop (); returnSuf; }
The second step is the method of calculating the suffix expression, which has been done on the OJ of Xiang-da http://202.197.224.59/exam/index.php/problem/read/id/1036
Private Static intCal (String s) {Stack<Integer> stack =NewStack<integer>(); for(inti = 0; I < s.length (); i++){ Charc =S.charat (i); BooleanFlag =false; intTMP = 0; if(c = = "") Continue; while(Is_num (c)) {tmp*= 10; TMP+ = (c-' 0 '); I++; C=S.charat (i); Flag=true; } if(flag) {i--; Stack.push (TMP); TMP= 0; } Else { intX1 =Stack.pop (); intx2 =Stack.pop (); intAns = 0; if(c = = ' * ') ans= x1 *x2; Else if(c = = '-')) ans= X2-X1; Else if(c = = ' + ')) ans= x1 +x2; Else if(c = = '/')) ans= x2/X1; Else if(c = = '% ') ans= x2%X1; Stack.push (ANS); } } returnStack.pop (); } Private Static BooleanIs_num (Charc) {if(c >= ' 0 ' && C <= ' 9 ') return true; return false; }View Code
So a little more complex problems can be done, but there are a few points in the middle and so on, as well as file operation and other requirements, time is pressing, I will step after step to complete the requirements.
Then the test sample ...
Calculate arithmetic expression (Java language implementation)