ImportJava.math.BigInteger;ImportJava.util.*; Public classMain { Public Static voidMain (string[] args) {Scanner scan=NewScanner (system.in); while(Scan.hasnext ()) {String str1=Scan.next (); Stack<BigInteger> num =NewStack<biginteger>(); Stack<Character> op =NewStack<character>(); // +,-,*,/,^,() for(intI=0;i<str1.length (); i++) { CharCH =Str1.charat (i); Switch(CH) { Case+: Case‘-‘: //These priority levels are greater than or equal to the current operator while(!op.empty () &&(Op.peek ()= = ' + ' | |Op.peek ()= = '-' | |Op.peek ()= = ' * ' | |Op.peek ()= = '/' | |Op.peek ()= = ' ^ ') {calc_stack (num, op); } op.push (CH); Break; Case‘*‘: Case‘/‘: while(!op.empty () &&(Op.peek ()= = ' * ' | |Op.peek ()= = '/' | |Op.peek ()= = ' ^ ') {calc_stack (num, op); } op.push (CH); Break; Case^: while(!op.empty () && op.peek () = = ' ^ ') {calc_stack (num, op); } op.push (CH); Break; Case‘(‘: Op.push (CH); Break; Case‘)‘: while(Op.peek ()! = ' (') {calc_stack (num, op); } //' (' Out of the stackOp.pop (); Break; default: String number=string.valueof (CH); while(I+1<str1.length () && character.isdigit (Str1.charat (i+1)) { number+=string.valueof (Str1.charat (i+1)); I++; } BigInteger Big=NewBigInteger (number); Num.push (big); Break; } } while(!Op.empty ()) {Calc_stack (num, op); } System.out.println (Num.pop ()); } scan.close (); } Private Static voidCalc_stack (Stack<biginteger>num, stack<character>op) { Charoperator =Op.pop (); BigInteger NUM1=Num.pop (); BigInteger num2=Num.pop (); Switch(operator) { Case' + ': Num.push (Num2.add (NUM1)); Break; Case'-': Num.push (Num2.subtract (NUM1)); Break; Case' * ': Num.push (num2.multiply (NUM1)); Break; Case'/': Num.push (Num2.divide (NUM1)); Break; Case' ^ ': Num.push (Num2.pow (Num1.intvalue ())); Break; } }}
Java expression evaluation