Ideas:
1 converting an expression to a suffix expression
2 Calculating suffix expressions using stacks
/*** Calculated values *@paramtext *@return */ Public Static intcount (String text) {Queue<String> queue=Changetopostorder (text); Stack<Integer> stack=NewStack<>(); intResult=0; while(!Queue.isempty ()) {String T=Queue.poll (); if(T.length () >1)//Digital{Stack.push (Integer.parseint (t)); } Else if(T.length () ==1) { if(Isyunsuanfu (t)) {CharC=t.charat (0); intRi=Stack.pop (); intLi=Stack.pop (); Switch(c) { Case+: Result=li+RI; Stack.push (result); Break; Case‘-‘: Result=li-RI; Stack.push (result); Break; Case‘*‘: Result=li*RI; Stack.push (result); Break; Case‘/‘: Result=li/RI; Stack.push (result); Break; default: Break; } } Else{Stack.push (Integer.parseint (t)); } } } returnStack.empty ()? 0: Stack.pop (); } //Change to Post order /*** Encountered digital direct output, encountered symbols, if it is higher than the top of the stack priority such as multiplication on the direct stack, * if it is below or equal to the top of the stack or the right parenthesis directly output stack top until the left parenthesis, and then press the stack *@paramtext *@return */ Public StaticQueue<string>Changetopostorder (String text) {Queue<String> queue=NewLinkedlist<>(); Stack<Character> stack=NewStack<>(); StringBuilder Temp=NewStringBuilder (); intlen=text.length (); for(inti=0;i<len;i++) { CharC=Text.charat (i); if(Isnumber (c)) {temp.append (c); if(i==len-1) {Queue.offer (temp.tostring ()); } }Else { //If the closing parenthesis is output directly until the opening parenthesis if(Temp.length ()!=0) {Queue.offer (temp.tostring ()); Temp.delete (0, Temp.length ()); } if(c== ') ') { while(Stack.peek ()! = ' (') {Queue.offer (Stack.pop ()+""); } //pop-up opening parenthesisStack.pop (); Continue; } //if the stack is empty, direct pressure stack if(Stack.empty () | | c== ' (') {Stack.push (c); Continue; } //priority comparison high-priority compression stack while(!stack.empty () &&!Ishigher (c, Stack.peek ())) {Queue.offer (Stack.pop ()+""); } stack.push (c); } } while(!Stack.empty ()) {Queue.offer (Stack.pop ()+""); } returnqueue; } Public Static BooleanIsnumber (Charc) {returnc>= ' 0 ' && c<= ' 9 '; } Public Static BooleanIsyunsuanfu (String s) {returnS.equals ("*") | | S.equals ("/") | | S.equals ("+") | | S.equals ("-"); } Public Static BooleanIshigher (CharCCharCMP) { returnPriority (c) >Priority (CMP); } Public Static intPriorityCharc) {intP=0; Switch(c) { Case‘*‘: P=2; Break; Case‘/‘: P=2; Break; Case+: P=1; Break; Case‘-‘: P=1; Break; default: Break; } returnp; }
The program is very wordy, have time to write again!
Java implementation of simple arithmetic expressions